Skip to main content
Glama
K02D

MCP Tabular Data Analysis Server

by K02D

detect_anomalies

Identify outliers in numeric data columns using statistical methods like z-score, IQR, or isolation forest to detect unusual patterns in CSV or SQLite files.

Instructions

Detect anomalies/outliers in a numeric column.

Args:
    file_path: Path to CSV or SQLite file
    column: Name of the numeric column to analyze
    method: Detection method - 'zscore' (default), 'iqr', or 'isolation_forest'
    threshold: Threshold for anomaly detection (default 3.0 for zscore, 1.5 for IQR)

Returns:
    Dictionary containing:
    - method: Detection method used
    - anomaly_count: Number of anomalies found
    - anomaly_indices: Row indices of anomalies
    - anomalies: The anomalous rows
    - statistics: Column statistics

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
columnYes
methodNozscore
thresholdNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'detect_anomalies' tool, decorated with @mcp.tool() for registration. It loads data, detects anomalies using z-score or IQR methods, and returns statistics and anomalous rows.
    @mcp.tool()
    def detect_anomalies(
        file_path: str,
        column: str,
        method: str = "zscore",
        threshold: float = 3.0,
    ) -> dict[str, Any]:
        """
        Detect anomalies/outliers in a numeric column.
        
        Args:
            file_path: Path to CSV or SQLite file
            column: Name of the numeric column to analyze
            method: Detection method - 'zscore' (default), 'iqr', or 'isolation_forest'
            threshold: Threshold for anomaly detection (default 3.0 for zscore, 1.5 for IQR)
        
        Returns:
            Dictionary containing:
            - method: Detection method used
            - anomaly_count: Number of anomalies found
            - anomaly_indices: Row indices of anomalies
            - anomalies: The anomalous rows
            - statistics: Column statistics
        """
        df = _load_data(file_path)
        
        if column not in df.columns:
            raise ValueError(f"Column '{column}' not found. Available: {df.columns.tolist()}")
        
        if not np.issubdtype(df[column].dtype, np.number):
            raise ValueError(f"Column '{column}' is not numeric")
        
        col_data = df[column].dropna()
        
        if method == "zscore":
            # Z-score method
            z_scores = np.abs(stats.zscore(col_data))
            anomaly_mask = z_scores > threshold
            anomaly_indices = col_data[anomaly_mask].index.tolist()
            
        elif method == "iqr":
            # Interquartile Range method
            q1 = col_data.quantile(0.25)
            q3 = col_data.quantile(0.75)
            iqr = q3 - q1
            lower_bound = q1 - threshold * iqr
            upper_bound = q3 + threshold * iqr
            anomaly_mask = (col_data < lower_bound) | (col_data > upper_bound)
            anomaly_indices = col_data[anomaly_mask].index.tolist()
            
        else:
            raise ValueError(f"Unknown method: {method}. Use 'zscore' or 'iqr'")
        
        anomalies_df = df.loc[anomaly_indices]
        
        return {
            "method": method,
            "threshold": threshold,
            "column": column,
            "anomaly_count": len(anomaly_indices),
            "anomaly_percentage": round(len(anomaly_indices) / len(col_data) * 100, 2),
            "anomaly_indices": anomaly_indices,
            "anomalies": anomalies_df.to_dict(orient="records"),
            "statistics": {
                "mean": float(col_data.mean()),
                "std": float(col_data.std()),
                "min": float(col_data.min()),
                "max": float(col_data.max()),
                "median": float(col_data.median()),
            }
        }
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it specifies input requirements (numeric column, file types), default values for parameters, and detailed return structure. However, it doesn't mention potential limitations like file size constraints or computational intensity of methods like 'isolation_forest'.

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 efficiently structured with a clear purpose statement followed by organized sections for Args and Returns. Every sentence adds value: the opening defines the tool, parameter explanations are necessary, and return details are essential given the output schema. No wasted words.

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

Completeness5/5

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

Given the tool's complexity (4 parameters, no annotations, 0% schema coverage) and the presence of an output schema, the description is complete. It covers purpose, parameters with semantics, and return structure, providing all necessary context for an agent to understand and invoke the tool correctly without redundancy.

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

Parameters5/5

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

The schema description coverage is 0%, so the description must compensate fully. It successfully adds meaning beyond the schema by explaining each parameter's purpose, default values, and method-specific threshold defaults. The 'Args' section provides clear semantics that the schema lacks entirely.

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 specific action ('detect anomalies/outliers'), the resource ('numeric column'), and the context ('in a CSV or SQLite file'). It distinguishes itself from siblings like 'statistical_test' or 'describe_dataset' by focusing specifically on anomaly detection rather than general analysis or description.

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 through parameter details (e.g., 'numeric column', 'CSV or SQLite file'), but doesn't explicitly state when to use this tool versus alternatives like 'data_quality_report' or 'statistical_test'. It provides context but lacks explicit guidance on tool selection among siblings.

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/K02D/mcp-tabular'

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