Skip to main content
Glama

filter_data

Filter data files by applying conditions to specific columns, such as equals, contains, greater_than, or less_than, and optionally save the filtered results.

Instructions

Filter data based on a condition.

Args: file_path: Path to the data file column: Column name to filter on condition: Filter condition (equals, contains, greater_than, less_than) value: Value to filter by output_path: Optional path to save filtered data

Returns: Information about the filtered data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
columnYes
conditionYes
valueYes
output_pathNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The filter_data tool implementation - filters data based on column conditions (equals, contains, greater_than, less_than) using pandas, with optional output to save filtered results
    @mcp.tool()
    def filter_data(file_path: str, column: str, condition: str, value: str, output_path: Optional[str] = None) -> str:
        """
        Filter data based on a condition.
        
        Args:
            file_path: Path to the data file
            column: Column name to filter on
            condition: Filter condition (equals, contains, greater_than, less_than)
            value: Value to filter by
            output_path: Optional path to save filtered data
        
        Returns:
            Information about the filtered data
        """
        try:
            import pandas as pd
            from pathlib import Path
            
            file_extension = Path(file_path).suffix.lower()
            
            # Load with pandas
            if file_extension == '.csv':
                df = pd.read_csv(file_path)
            elif file_extension == '.json':
                df = pd.read_json(file_path)
            elif file_extension in ['.xlsx', '.xls']:
                df = pd.read_excel(file_path)
            elif file_extension == '.tsv':
                df = pd.read_csv(file_path, sep='\t')
            else:
                df = pd.read_csv(file_path)
            
            if column not in df.columns:
                return f"Error: Column '{column}' not found. Available columns: {list(df.columns)}"
            
            original_rows = len(df)
            
            # Apply filter
            if condition == "equals":
                filtered_df = df[df[column].astype(str) == value]
            elif condition == "contains":
                filtered_df = df[df[column].astype(str).str.contains(value, case=False, na=False)]
            elif condition == "greater_than":
                try:
                    numeric_value = float(value)
                    filtered_df = df[pd.to_numeric(df[column], errors='coerce') > numeric_value]
                except ValueError:
                    return f"Error: Cannot convert '{value}' to number for greater_than comparison"
            elif condition == "less_than":
                try:
                    numeric_value = float(value)
                    filtered_df = df[pd.to_numeric(df[column], errors='coerce') < numeric_value]
                except ValueError:
                    return f"Error: Cannot convert '{value}' to number for less_than comparison"
            else:
                return f"Error: Unknown condition '{condition}'. Use: equals, contains, greater_than, less_than"
            
            result = {
                "original_rows": original_rows,
                "filtered_rows": len(filtered_df),
                "filter_applied": f"{column} {condition} {value}"
            }
            
            # If output path is specified, save filtered data
            if output_path:
                output_extension = Path(output_path).suffix.lower()
                if output_extension == '.csv':
                    filtered_df.to_csv(output_path, index=False)
                elif output_extension == '.json':
                    filtered_df.to_json(output_path, orient='records', indent=2)
                elif output_extension in ['.xlsx', '.xls']:
                    filtered_df.to_excel(output_path, index=False)
                else:
                    # Default to CSV
                    filtered_df.to_csv(output_path, index=False)
                result["saved_to"] = output_path
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            return f"Error filtering data: {str(e)}\n{traceback.format_exc()}"
  • The @mcp.tool() decorator that registers filter_data as an MCP tool
    @mcp.tool()
Behavior2/5

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

With no annotations provided, the description carries the full burden but only states basic functionality without disclosing behavioral traits like file format support, error handling, performance, or whether it modifies original files. It mentions optional output saving but lacks details on defaults or effects.

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

Conciseness4/5

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

The description is appropriately sized and front-loaded with the core purpose, followed by a structured Args and Returns section. Sentences are efficient, though the parameter explanations could be more detailed without sacrificing brevity.

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 5 parameters with 0% schema coverage and no annotations, the description partially compensates by listing parameters and mentioning an output schema exists, but it lacks details on data formats, error cases, and integration with siblings. It's minimally adequate but has clear gaps for a data filtering tool.

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

Parameters3/5

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

Schema description coverage is 0%, so the description must compensate. It lists parameters with brief explanations (e.g., 'Column name to filter on'), adding some meaning beyond schema titles, but doesn't specify formats (e.g., file types for 'file_path', data types for 'value') or constraints, leaving gaps in understanding.

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 states 'Filter data based on a condition' which is a clear verb+resource but remains vague about the data format (e.g., CSV, JSON) and lacks differentiation from sibling tools like 'sort_data' or 'get_data_sample'. It specifies the action but not the context or uniqueness.

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 'sort_data' or 'get_data_sample' for data manipulation, nor prerequisites like data loading. The description implies filtering but doesn't specify scenarios or exclusions, leaving usage unclear.

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/moeloubani/visidata-mcp'

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