Skip to main content
Glama
NovaAI-innovation

CSV MCP Server

filter_data

Filter CSV data by applying conditions to columns, returning matching rows with optional row limits for data analysis.

Instructions

Filter CSV data based on conditions.

Args:
    filename: Name of the CSV file
    conditions: Dictionary of column conditions. 
               Simple: {"column": "value"}
               Complex: {"column": {"gt": 5, "lt": 10, "contains": "text"}}
    limit: Optional limit on number of rows to return

Returns:
    Dictionary with filtered data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
conditionsYes
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Registration and handler for the 'filter_data' MCP tool. This function is decorated with @mcp.tool() making it available as an MCP tool, and it delegates the logic to CSVManager.filter_data.
    @mcp.tool()
    def filter_data(
        filename: str,
        conditions: Dict[str, Any],
        limit: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        Filter CSV data based on conditions.
        
        Args:
            filename: Name of the CSV file
            conditions: Dictionary of column conditions. 
                       Simple: {"column": "value"}
                       Complex: {"column": {"gt": 5, "lt": 10, "contains": "text"}}
            limit: Optional limit on number of rows to return
        
        Returns:
            Dictionary with filtered data
        """
        try:
            return csv_manager.filter_data(filename, conditions, limit)
        except Exception as e:
            return {"success": False, "error": str(e)}
  • Core implementation of data filtering logic in CSVManager class. Applies conditions to pandas DataFrame and returns filtered results.
    def filter_data(self, filename: str, conditions: Dict[str, Any], limit: Optional[int] = None) -> Dict[str, Any]:
        """Filter CSV data based on conditions."""
        filepath = self._get_file_path(filename)
        
        if not filepath.exists():
            raise FileNotFoundError(f"CSV file '{filename}' not found")
        
        try:
            df = pd.read_csv(filepath)
            
            # Apply filters
            for column, condition in conditions.items():
                if column not in df.columns:
                    raise ValueError(f"Column '{column}' not found in CSV")
                
                if isinstance(condition, dict):
                    # Handle complex conditions like {"gt": 5, "lt": 10}
                    if "eq" in condition:
                        df = df[df[column] == condition["eq"]]
                    if "ne" in condition:
                        df = df[df[column] != condition["ne"]]
                    if "gt" in condition:
                        df = df[df[column] > condition["gt"]]
                    if "gte" in condition:
                        df = df[df[column] >= condition["gte"]]
                    if "lt" in condition:
                        df = df[df[column] < condition["lt"]]
                    if "lte" in condition:
                        df = df[df[column] <= condition["lte"]]
                    if "contains" in condition:
                        df = df[df[column].astype(str).str.contains(condition["contains"], na=False)]
                else:
                    # Simple equality filter
                    df = df[df[column] == condition]
            
            # Apply limit if specified
            if limit and limit > 0:
                df = df.head(limit)
            
            return {
                "success": True,
                "filename": filename,
                "conditions": conditions,
                "filtered_data": df.to_dict('records'),
                "filtered_rows": len(df),
                "original_rows": len(pd.read_csv(filepath))
            }
        except Exception as e:
            logger.error(f"Failed to filter data: {e}")
            raise
  • Function signature defines the input schema (parameters) and output type for the MCP tool.
    def filter_data(
        filename: str,
        conditions: Dict[str, Any],
        limit: Optional[int] = None
    ) -> Dict[str, Any]:
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses that the tool returns filtered data as a dictionary, which is useful, but lacks details on error handling (e.g., for invalid files or conditions), performance implications, or side effects. The description doesn't contradict annotations, but it's minimal for a tool with parameters and no annotation support.

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 well-structured and front-loaded with the core purpose, followed by clear sections for Args and Returns. Each sentence adds value: the first states the purpose, and the subsequent ones explain parameters and output without redundancy. It's appropriately sized for a tool with three parameters.

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 complexity (3 parameters, nested objects, no annotations, but an output schema exists), the description is moderately complete. It covers the purpose and parameters adequately, and the output schema handles return values, but it lacks usage guidelines and detailed behavioral context. For a data filtering tool with siblings, more guidance would improve completeness.

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

Parameters4/5

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

With 0% schema description coverage, the description compensates well by explaining all three parameters: 'filename', 'conditions' (with examples for simple and complex cases), and 'limit'. It adds meaningful context beyond the schema's basic types, such as the structure of conditions and the optional nature of limit. However, it doesn't cover edge cases like file paths or condition syntax details.

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 tool's purpose: 'Filter CSV data based on conditions.' It specifies the verb ('filter'), resource ('CSV data'), and mechanism ('conditions'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from siblings like 'group_data' or 'sort_data' that also manipulate CSV data, which prevents a perfect score.

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. With siblings like 'group_data', 'sort_data', and 'read_csv' available, there's no mention of specific scenarios, prerequisites, or exclusions for using 'filter_data'. This lack of context leaves the agent to infer usage from the purpose alone.

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/NovaAI-innovation/csv-mcp-server'

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