Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

get_correlation_matrix

Compute pairwise correlations of numeric columns in your CSV, supporting Pearson (default) and other methods, with optional minimum correlation filter.

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: calculates correlation matrix for numeric columns using pandas corr() with pearson/spearman/kendall methods, optionally filters by columns and min_correlation threshold, and returns correlation matrix plus highly correlated pairs.
    async def get_correlation_matrix(
        session_id: str,
        method: str = "pearson",
        columns: list[str] | None = None,
        min_correlation: float | None = 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: {e!s}")
            return {"success": False, "error": str(e)}
  • MCP tool registration: decorated with @mcp.tool, exposing get_correlation_matrix to clients and delegating to the handler.
    @mcp.tool
    async def get_correlation_matrix(
        session_id: str,
        method: str = "pearson",
        columns: list[str] | None = None,
        min_correlation: float | None = 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 alias that connects the registration in server.py to the handler in tools/analytics.py.
    from .tools.analytics import get_correlation_matrix as _get_correlation_matrix
Behavior2/5

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

With no annotations and a minimal description, there is no disclosure of behavioral traits such as whether the tool modifies data, performance implications, or output structure. The description carries the full burden but adds little.

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

Conciseness3/5

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

The description is very short (one sentence), which is concise but lacks structure. It has no wasted words, but brevity comes at the cost of completeness.

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

Completeness2/5

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

Given the four parameters with no schema descriptions, no annotations, and no mention of the output schema (which exists), the description is insufficient to fully understand the tool's usage and behavior.

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?

Schema coverage is 0%, yet the description only mentions 'numeric columns' without clarifying the purpose of each parameter (e.g., 'method', 'columns', 'min_correlation'). No added value beyond the implicit schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('calculate') and the resource ('correlation matrix for numeric columns'), effectively distinguishing it from sibling tools like 'get_column_statistics' or 'detect_outliers'.

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?

No guidance is provided on when to use this tool versus alternatives, or on prerequisites. The description lacks context for appropriate usage.

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