Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

find_anomalies

Detect data anomalies in CSV files using multiple statistical methods to identify outliers and irregularities for data quality assessment.

Instructions

Find anomalies in the data using multiple detection methods.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
columnsNo
sensitivityNo
methodsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function executing the find_anomalies tool. Implements statistical (Z-score & IQR), pattern-based rarity/format checks, and missing value pattern detection. Adjustable by sensitivity and methods.
    async def find_anomalies(
        session_id: str,
        columns: Optional[List[str]] = None,
        sensitivity: float = 0.95,
        methods: Optional[List[str]] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Find anomalies in the data using multiple detection methods.
        
        Args:
            session_id: Session identifier
            columns: Columns to check (None for all)
            sensitivity: Detection sensitivity (0.0 to 1.0, higher = more sensitive)
            methods: Detection methods to use (default: ["statistical", "pattern"])
            ctx: FastMCP context
            
        Returns:
            Dict with anomaly detection results
        """
        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
            
            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}"}
                target_cols = columns
            else:
                target_cols = df.columns.tolist()
            
            if not methods:
                methods = ["statistical", "pattern", "missing"]
            
            anomalies = {
                "summary": {
                    "total_anomalies": 0,
                    "affected_rows": set(),
                    "affected_columns": []
                },
                "by_column": {},
                "by_method": {}
            }
            
            # Statistical anomalies (outliers)
            if "statistical" in methods:
                numeric_cols = df[target_cols].select_dtypes(include=[np.number]).columns
                statistical_anomalies = {}
                
                for col in numeric_cols:
                    col_data = df[col].dropna()
                    if len(col_data) > 0:
                        # Z-score method
                        z_scores = np.abs((col_data - col_data.mean()) / col_data.std())
                        z_threshold = 3 * (1 - sensitivity + 0.5)  # Adjust threshold based on sensitivity
                        z_anomalies = df.index[z_scores > z_threshold].tolist()
                        
                        # IQR method
                        Q1 = col_data.quantile(0.25)
                        Q3 = col_data.quantile(0.75)
                        IQR = Q3 - Q1
                        iqr_factor = 1.5 * (2 - sensitivity)  # Adjust factor based on sensitivity
                        lower = Q1 - iqr_factor * IQR
                        upper = Q3 + iqr_factor * IQR
                        iqr_anomalies = df.index[(df[col] < lower) | (df[col] > upper)].tolist()
                        
                        # Combine both methods
                        combined_anomalies = list(set(z_anomalies) | set(iqr_anomalies))
                        
                        if combined_anomalies:
                            statistical_anomalies[col] = {
                                "anomaly_count": len(combined_anomalies),
                                "anomaly_indices": combined_anomalies[:100],
                                "anomaly_values": df.loc[combined_anomalies[:10], col].tolist(),
                                "mean": float(col_data.mean()),
                                "std": float(col_data.std()),
                                "lower_bound": float(lower),
                                "upper_bound": float(upper)
                            }
                            
                            anomalies["summary"]["total_anomalies"] += len(combined_anomalies)
                            anomalies["summary"]["affected_rows"].update(combined_anomalies)
                            anomalies["summary"]["affected_columns"].append(col)
                
                if statistical_anomalies:
                    anomalies["by_method"]["statistical"] = statistical_anomalies
            
            # Pattern anomalies
            if "pattern" in methods:
                pattern_anomalies = {}
                
                for col in target_cols:
                    if df[col].dtype == object or pd.api.types.is_string_dtype(df[col]):
                        col_data = df[col].dropna()
                        if len(col_data) > 0:
                            # Detect unusual patterns
                            value_counts = col_data.value_counts()
                            total_count = len(col_data)
                            
                            # Find rare values (appearing less than threshold)
                            threshold = (1 - sensitivity) * 0.01  # Adjust threshold
                            rare_values = value_counts[value_counts / total_count < threshold]
                            
                            if len(rare_values) > 0:
                                rare_indices = df[df[col].isin(rare_values.index)].index.tolist()
                                
                                # Check for format anomalies (e.g., different case, special characters)
                                common_pattern = None
                                if len(value_counts) > 10:
                                    # Detect common pattern from frequent values
                                    top_values = value_counts.head(10).index
                                    
                                    # Check if most values are uppercase/lowercase
                                    upper_count = sum(1 for v in top_values if str(v).isupper())
                                    lower_count = sum(1 for v in top_values if str(v).islower())
                                    
                                    if upper_count > 7:
                                        common_pattern = "uppercase"
                                    elif lower_count > 7:
                                        common_pattern = "lowercase"
                                
                                format_anomalies = []
                                if common_pattern:
                                    for idx, val in col_data.items():
                                        if common_pattern == "uppercase" and not str(val).isupper():
                                            format_anomalies.append(idx)
                                        elif common_pattern == "lowercase" and not str(val).islower():
                                            format_anomalies.append(idx)
                                
                                all_pattern_anomalies = list(set(rare_indices + format_anomalies))
                                
                                if all_pattern_anomalies:
                                    pattern_anomalies[col] = {
                                        "anomaly_count": len(all_pattern_anomalies),
                                        "rare_values": rare_values.head(10).to_dict(),
                                        "anomaly_indices": all_pattern_anomalies[:100],
                                        "common_pattern": common_pattern
                                    }
                                    
                                    anomalies["summary"]["total_anomalies"] += len(all_pattern_anomalies)
                                    anomalies["summary"]["affected_rows"].update(all_pattern_anomalies)
                                    if col not in anomalies["summary"]["affected_columns"]:
                                        anomalies["summary"]["affected_columns"].append(col)
                
                if pattern_anomalies:
                    anomalies["by_method"]["pattern"] = pattern_anomalies
            
            # Missing value anomalies
            if "missing" in methods:
                missing_anomalies = {}
                
                for col in target_cols:
                    null_mask = df[col].isna()
                    null_count = null_mask.sum()
                    
                    if null_count > 0:
                        null_ratio = null_count / len(df)
                        
                        # Check for suspicious missing patterns
                        if 0 < null_ratio < 0.5:  # Partially missing
                            # Check if missing values are clustered
                            null_indices = df.index[null_mask].tolist()
                            
                            # Check for sequential missing values
                            sequential_missing = []
                            if len(null_indices) > 1:
                                for i in range(len(null_indices) - 1):
                                    if null_indices[i+1] - null_indices[i] == 1:
                                        if not sequential_missing or null_indices[i] - sequential_missing[-1][-1] == 1:
                                            if sequential_missing:
                                                sequential_missing[-1].append(null_indices[i+1])
                                            else:
                                                sequential_missing.append([null_indices[i], null_indices[i+1]])
                            
                            # Flag as anomaly if there are suspicious patterns
                            is_anomaly = len(sequential_missing) > 0 and len(sequential_missing) > len(null_indices) * 0.3
                            
                            if is_anomaly or (null_ratio > 0.1 and null_ratio < 0.3):
                                missing_anomalies[col] = {
                                    "missing_count": int(null_count),
                                    "missing_ratio": round(null_ratio, 4),
                                    "missing_indices": null_indices[:100],
                                    "sequential_clusters": len(sequential_missing),
                                    "pattern": "clustered" if sequential_missing else "random"
                                }
                                
                                anomalies["summary"]["affected_columns"].append(col)
                
                if missing_anomalies:
                    anomalies["by_method"]["missing"] = missing_anomalies
            
            # Organize anomalies by column
            for method_name, method_anomalies in anomalies["by_method"].items():
                for col, col_anomalies in method_anomalies.items():
                    if col not in anomalies["by_column"]:
                        anomalies["by_column"][col] = {}
                    anomalies["by_column"][col][method_name] = col_anomalies
            
            # Convert set to list for JSON serialization
            anomalies["summary"]["affected_rows"] = list(anomalies["summary"]["affected_rows"])[:1000]
            anomalies["summary"]["affected_columns"] = list(set(anomalies["summary"]["affected_columns"]))
            
            # Calculate anomaly score
            total_cells = len(df) * len(target_cols)
            anomaly_cells = len(anomalies["summary"]["affected_rows"]) * len(anomalies["summary"]["affected_columns"])
            anomaly_score = min(anomaly_cells / total_cells, 1.0) * 100
            
            anomalies["summary"]["anomaly_score"] = round(anomaly_score, 2)
            anomalies["summary"]["severity"] = (
                "high" if anomaly_score > 10
                else "medium" if anomaly_score > 5
                else "low"
            )
            
            session.record_operation(OperationType.ANOMALY_DETECTION, {
                "methods": methods,
                "sensitivity": sensitivity,
                "anomalies_found": anomalies["summary"]["total_anomalies"]
            })
            
            return {
                "success": True,
                "anomalies": anomalies,
                "columns_analyzed": target_cols,
                "methods_used": methods,
                "sensitivity": sensitivity
            }
            
        except Exception as e:
            logger.error(f"Error finding anomalies: {str(e)}")
            return {"success": False, "error": str(e)}
  • FastMCP tool registration using @mcp.tool decorator. Defines input schema via annotated parameters (session_id, columns, sensitivity, methods, ctx) and delegates execution to the core handler in validation.py.
    @mcp.tool
    async def find_anomalies(
        session_id: str,
        columns: Optional[List[str]] = None,
        sensitivity: float = 0.95,
        methods: Optional[List[str]] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Find anomalies in the data using multiple detection methods."""
        return await _find_anomalies(session_id, columns, sensitivity, methods, ctx)
  • Input schema inferred from function parameters in the registered tool definition.
    async def find_anomalies(
        session_id: str,
        columns: Optional[List[str]] = None,
        sensitivity: float = 0.95,
        methods: Optional[List[str]] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Find anomalies in the data using multiple detection methods."""
        return await _find_anomalies(session_id, columns, sensitivity, methods, ctx)
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Find anomalies' implies a read-only analysis operation, it doesn't specify whether this modifies data, requires specific data states, has performance characteristics, or what constitutes an 'anomaly'. The mention of 'multiple detection methods' hints at configurability but lacks concrete behavioral details.

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 a single, efficient sentence that communicates the core purpose without unnecessary words. It's appropriately sized for the tool's complexity and gets straight to the point with zero wasted verbiage.

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 has 4 parameters with 0% schema coverage and no annotations, but does have an output schema, the description is minimally adequate. The output schema will document return values, reducing the burden on the description. However, for a data analysis tool with multiple parameters, more guidance on parameter usage and behavioral characteristics would be beneficial.

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 provides no information about what 'session_id', 'columns', 'sensitivity', or 'methods' mean or how they affect anomaly detection. The description mentions 'multiple detection methods' which relates to the 'methods' parameter but doesn't explain what methods are available or how to specify them.

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 'Find anomalies in the data using multiple detection methods' clearly states the verb ('Find') and resource ('anomalies in the data'), with the method ('multiple detection methods') providing some specificity. However, it doesn't explicitly differentiate from sibling tools like 'detect_outliers' or 'check_data_quality', leaving some ambiguity about when to use this particular anomaly detection approach.

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 like 'detect_outliers' or 'check_data_quality'. There's no mention of prerequisites, appropriate data contexts, or comparative strengths/weaknesses of the 'multiple detection methods' approach.

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