Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

detect_outliers

Detect outliers in numeric columns of your CSV data using configurable methods like IQR and adjustable thresholds.

Instructions

Detect outliers in numeric columns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
columnsNo
methodNoiqr
thresholdNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that detects outliers in numeric columns using IQR or Z-Score methods. Validates session/columns, computes outlier boundaries, and returns structured results with counts, percentages, and indices.
    async def detect_outliers(
        session_id: str,
        columns: list[str] | None = None,
        method: str = "iqr",
        threshold: float = 1.5,
        ctx: Context = None,
    ) -> dict[str, Any]:
        """
        Detect outliers in numeric columns.
    
        Args:
            session_id: Session identifier
            columns: Columns to check (None for all numeric)
            method: Detection method ('iqr', 'zscore', 'isolation_forest')
            threshold: Threshold for outlier detection (1.5 for IQR, 3 for z-score)
            ctx: FastMCP context
    
        Returns:
            Dict with outlier information
        """
        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 numeric 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"}
    
            outliers = {}
    
            if method == "iqr":
                for col in numeric_df.columns:
                    Q1 = numeric_df[col].quantile(0.25)
                    Q3 = numeric_df[col].quantile(0.75)
                    IQR = Q3 - Q1
    
                    lower_bound = Q1 - threshold * IQR
                    upper_bound = Q3 + threshold * IQR
    
                    outlier_mask = (numeric_df[col] < lower_bound) | (numeric_df[col] > upper_bound)
                    outlier_indices = df.index[outlier_mask].tolist()
    
                    outliers[col] = {
                        "method": "IQR",
                        "lower_bound": float(lower_bound),
                        "upper_bound": float(upper_bound),
                        "outlier_count": len(outlier_indices),
                        "outlier_percentage": round(len(outlier_indices) / len(df) * 100, 2),
                        "outlier_indices": outlier_indices[:100],  # Limit to first 100
                        "q1": float(Q1),
                        "q3": float(Q3),
                        "iqr": float(IQR),
                    }
    
            elif method == "zscore":
                for col in numeric_df.columns:
                    z_scores = np.abs(
                        (numeric_df[col] - numeric_df[col].mean()) / numeric_df[col].std()
                    )
                    outlier_mask = z_scores > threshold
                    outlier_indices = df.index[outlier_mask].tolist()
    
                    outliers[col] = {
                        "method": "Z-Score",
                        "threshold": threshold,
                        "outlier_count": len(outlier_indices),
                        "outlier_percentage": round(len(outlier_indices) / len(df) * 100, 2),
                        "outlier_indices": outlier_indices[:100],  # Limit to first 100
                        "mean": float(numeric_df[col].mean()),
                        "std": float(numeric_df[col].std()),
                    }
    
            else:
                return {"success": False, "error": f"Unknown method: {method}"}
    
            # Summary statistics
            total_outliers = sum(info["outlier_count"] for info in outliers.values())
    
            session.record_operation(
                OperationType.ANALYZE,
                {
                    "type": "outlier_detection",
                    "method": method,
                    "threshold": threshold,
                    "columns": list(outliers.keys()),
                },
            )
    
            return {
                "success": True,
                "method": method,
                "threshold": threshold,
                "outliers": outliers,
                "total_outliers": total_outliers,
                "columns_analyzed": list(outliers.keys()),
            }
    
        except Exception as e:
            logger.error(f"Error detecting outliers: {e!s}")
            return {"success": False, "error": str(e)}
  • MCP tool registration using @mcp.tool decorator. Imports the handler from analytics module and delegates to it.
    @mcp.tool
    async def detect_outliers(
        session_id: str,
        columns: list[str] | None = None,
        method: str = "iqr",
        threshold: float = 1.5,
        ctx: Context = None,
    ) -> dict[str, Any]:
        """Detect outliers in numeric columns."""
        return await _detect_outliers(session_id, columns, method, threshold, ctx)
  • Tool capability listing in the server info/health check response, documenting detect_outliers as part of data_analysis capabilities.
            "data_analysis": [
                "get_statistics",
                "correlation_matrix",
                "group_by_aggregate",
                "value_counts",
                "detect_outliers",
                "profile_data",
            ],
            "data_validation": ["validate_schema", "check_data_quality", "find_anomalies"],
            "session_management": ["multi_session_support", "session_isolation", "auto_cleanup"],
        },
        "supported_formats": ["csv", "tsv", "json", "excel", "parquet", "html", "markdown"],
        "max_file_size_mb": int(os.getenv("CSV_MAX_FILE_SIZE", "1024")),
        "session_timeout_minutes": int(os.getenv("CSV_SESSION_TIMEOUT", "60")),
    }
  • Import of detect_outliers from the analytics module into the server's registration namespace.
    from .tools.analytics import detect_outliers as _detect_outliers
    from .tools.analytics import get_column_statistics as _get_column_statistics
    from .tools.analytics import get_correlation_matrix as _get_correlation_matrix
    from .tools.analytics import get_statistics as _get_statistics
    from .tools.analytics import get_value_counts as _get_value_counts
    from .tools.analytics import group_by_aggregate as _group_by_aggregate
    from .tools.analytics import profile_data as _profile_data
  • Call to detect_outliers from within profile_data helper to include outlier information in the data profile.
    if include_outliers:
        outlier_result = await detect_outliers(session_id, ctx=ctx)
        if outlier_result["success"]:
            profile["outliers"] = {
                col: {"count": info["outlier_count"], "percentage": info["outlier_percentage"]}
                for col, info in outlier_result["outliers"].items()
            }
Behavior2/5

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

With no annotations, the description carries full burden but only mentions outlier detection without disclosing method defaults, threshold behavior, or side effects. The output schema exists but is not described, leaving behavioral details opaque.

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 a single concise sentence, which is appropriate but lacks any structure such as bullet points or front-loading of critical details beyond the purpose.

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

Completeness1/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, no annotations, and a sibling with similar purpose, the description is severely incomplete. It omits method options, column specification, threshold meaning, and output format.

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

Parameters1/5

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

Schema description coverage is 0%; the description adds no meaning to any of the 4 parameters. Defaults in the schema provide minimal info, but the description does not compensate for the lack of parameter documentation.

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 verb 'detect' and the resource 'outliers in numeric columns', but does not differentiate from the sibling tool 'find_anomalies' which may have overlapping functionality.

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 on when to use this tool versus alternatives like 'find_anomalies', and no prerequisites or context are provided.

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