Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

filter_rows

Filter rows in a CSV dataset by applying conditions with AND or OR logic to include only matching records.

Instructions

Filter rows based on conditions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
conditionsYes
modeNoand

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function for filter_rows tool. Takes session_id, conditions (list of dicts with column/operator/value), and mode ('and'/'or'). Uses pandas to build a boolean mask from conditions, applies it to the DataFrame, records the operation, and returns row counts.
    async def filter_rows(
        session_id: str, conditions: list[dict[str, Any]], mode: str = "and", ctx: Context = None
    ) -> dict[str, Any]:
        """
        Filter rows based on conditions.
    
        Args:
            session_id: Session identifier
            conditions: List of filter conditions, each with:
                - column: Column name
                - operator: One of '==', '!=', '>', '<', '>=', '<=', 'contains', 'starts_with', 'ends_with', 'in', 'not_in', 'is_null', 'not_null'
                - value: Value to compare (not needed for is_null/not_null)
            mode: 'and' or 'or' to combine multiple conditions
            ctx: FastMCP context
    
        Returns:
            Dict with success status and filtered row count
        """
        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
            mask = pd.Series([True] * len(df))
    
            for condition in conditions:
                column = condition.get("column")
                operator = condition.get("operator")
                value = condition.get("value")
    
                if column not in df.columns:
                    return {"success": False, "error": f"Column '{column}' not found"}
    
                col_data = df[column]
    
                if operator == "==":
                    condition_mask = col_data == value
                elif operator == "!=":
                    condition_mask = col_data != value
                elif operator == ">":
                    condition_mask = col_data > value
                elif operator == "<":
                    condition_mask = col_data < value
                elif operator == ">=":
                    condition_mask = col_data >= value
                elif operator == "<=":
                    condition_mask = col_data <= value
                elif operator == "contains":
                    condition_mask = col_data.astype(str).str.contains(str(value), na=False)
                elif operator == "starts_with":
                    condition_mask = col_data.astype(str).str.startswith(str(value), na=False)
                elif operator == "ends_with":
                    condition_mask = col_data.astype(str).str.endswith(str(value), na=False)
                elif operator == "in":
                    condition_mask = col_data.isin(value if isinstance(value, list) else [value])
                elif operator == "not_in":
                    condition_mask = ~col_data.isin(value if isinstance(value, list) else [value])
                elif operator == "is_null":
                    condition_mask = col_data.isna()
                elif operator == "not_null":
                    condition_mask = col_data.notna()
                else:
                    return {"success": False, "error": f"Unknown operator: {operator}"}
    
                if mode == "and":
                    mask = mask & condition_mask
                else:
                    mask = mask | condition_mask
    
            session.df = df[mask].reset_index(drop=True)
            session.record_operation(
                OperationType.FILTER,
                {
                    "conditions": conditions,
                    "mode": mode,
                    "rows_before": len(df),
                    "rows_after": len(session.df),
                },
            )
    
            return {
                "success": True,
                "rows_before": len(df),
                "rows_after": len(session.df),
                "rows_filtered": len(df) - len(session.df),
            }
    
        except Exception as e:
            logger.error(f"Error filtering rows: {e!s}")
            return {"success": False, "error": str(e)}
  • MCP tool registration decorator wrapping filter_rows. Imports _filter_rows from transformations module and delegates the call.
    @mcp.tool
    async def filter_rows(
        session_id: str, conditions: list[dict[str, Any]], mode: str = "and", ctx: Context = None
    ) -> dict[str, Any]:
        """Filter rows based on conditions."""
        return await _filter_rows(session_id, conditions, mode, ctx)
  • Server info listing 'filter_rows' as a data_manipulation capability.
    return {
        "name": "CSV Editor",
        "version": "2.0.0",
        "description": "A comprehensive MCP server for CSV file operations and data analysis",
        "capabilities": {
            "data_io": [
                "load_csv",
                "load_csv_from_url",
                "load_csv_from_content",
                "export_csv",
                "multiple_export_formats",
            ],
            "data_manipulation": [
                "filter_rows",
                "sort_data",
                "select_columns",
                "rename_columns",
                "add_column",
                "remove_columns",
                "change_column_type",
                "fill_missing_values",
                "remove_duplicates",
            ],
            "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")),
    }
  • OperationType enum defining FILTER as 'filter' used for recording filter operations in session history.
    class OperationType(str, Enum):
        """Types of operations that can be performed."""
    
        LOAD = "load"
        FILTER = "filter"
        SORT = "sort"
        TRANSFORM = "transform"
        AGGREGATE = "aggregate"
        EXPORT = "export"
        ANALYZE = "analyze"
        UPDATE_COLUMN = "update_column"
        ADD_COLUMN = "add_column"
        REMOVE_COLUMN = "remove_column"
        RENAME = "rename"
        SELECT = "select"
        CHANGE_TYPE = "change_type"
        FILL_MISSING = "fill_missing"
        REMOVE_DUPLICATES = "remove_duplicates"
        GROUP_BY = "group_by"
        VALIDATE = "validate"
        PROFILE = "profile"
        QUALITY_CHECK = "quality_check"
        ANOMALY_DETECTION = "anomaly_detection"
Behavior1/5

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

With no annotations provided, the description carries full burden for behavior. It does not disclose whether filtering is destructive or temporary, nor the effect on session state. Critical behavior is omitted.

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

Conciseness2/5

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

A single sentence is too brief for a tool with 3 parameters and an output schema. It lacks necessary details while not being effectively concise.

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 complexity (3 params, output schema exists), the description is severely incomplete. No information on return values, behavior, or how to construct conditions.

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 extra meaning to the parameters (session_id, conditions, mode). The structure of 'conditions' and meaning of 'mode' remain unexplained.

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

Purpose3/5

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

The description 'Filter rows based on conditions' indicates a verb and resource, but the resource is vague ('rows' of what?). It does not differentiate from sibling tools like 'select_columns' or 'sort_data'.

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 such as 'select_columns' or 'detect_outliers'. No context provided 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