Skip to main content
Glama
NovaAI-innovation

CSV MCP Server

sort_data

Sort CSV data by specified columns to organize information in ascending or descending order. Define columns, set sort direction, and optionally limit results for structured data analysis.

Instructions

Sort CSV data by specified columns.

Args:
    filename: Name of the CSV file
    columns: Column name or list of column names to sort by
    ascending: Whether to sort in ascending order
    limit: Optional limit on number of rows to return

Returns:
    Dictionary with sorted data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
columnsYes
ascendingNo
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core handler implementation that loads CSV with pandas, validates sort columns, performs sorting using sort_values, applies limit if specified, and returns sorted data.
    def sort_data(self, filename: str, columns: Union[str, List[str]], ascending: bool = True, limit: Optional[int] = None) -> Dict[str, Any]:
        """Sort CSV data by specified columns."""
        filepath = self._get_file_path(filename)
        
        if not filepath.exists():
            raise FileNotFoundError(f"CSV file '{filename}' not found")
        
        try:
            df = pd.read_csv(filepath)
            
            # Ensure columns is a list
            if isinstance(columns, str):
                columns = [columns]
            
            # Validate columns exist
            for col in columns:
                if col not in df.columns:
                    raise ValueError(f"Column '{col}' not found in CSV")
            
            # Sort data
            df_sorted = df.sort_values(by=columns, ascending=ascending)
            
            # Apply limit if specified
            if limit and limit > 0:
                df_sorted = df_sorted.head(limit)
            
            return {
                "success": True,
                "filename": filename,
                "sort_columns": columns,
                "ascending": ascending,
                "sorted_data": df_sorted.to_dict('records'),
                "total_rows": len(df_sorted)
            }
        except Exception as e:
            logger.error(f"Failed to sort data: {e}")
            raise
  • MCP tool registration for 'sort_data' using @mcp.tool() decorator. Defines input schema via parameters and delegates execution to CSVManager.sort_data.
    @mcp.tool()
    def sort_data(
        filename: str,
        columns: Union[str, List[str]],
        ascending: bool = True,
        limit: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        Sort CSV data by specified columns.
        
        Args:
            filename: Name of the CSV file
            columns: Column name or list of column names to sort by
            ascending: Whether to sort in ascending order
            limit: Optional limit on number of rows to return
        
        Returns:
            Dictionary with sorted data
        """
        try:
            return csv_manager.sort_data(filename, columns, ascending, limit)
        except Exception as e:
            return {"success": False, "error": str(e)}
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 of behavioral disclosure. While it mentions the basic operation (sorting CSV data) and return format (dictionary), it doesn't describe important behaviors like whether the original file is modified, what happens with invalid columns, how ties are broken in sorting, memory/performance considerations for large files, or error handling. For a data manipulation tool with zero annotation coverage, this leaves significant gaps.

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 well-structured with a clear purpose statement followed by organized Args and Returns sections. Each sentence serves a purpose, though the 'Returns' section could be more specific about the dictionary structure. The formatting with clear sections makes it easy to parse.

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 4 parameters with 0% schema coverage and no annotations, the description does a reasonable job explaining parameter semantics but lacks behavioral context. The existence of an output schema means the description doesn't need to detail return values, but for a data manipulation tool that could have side effects or specific constraints, more behavioral information would be helpful for safe agent usage.

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?

The description provides meaningful parameter information beyond the schema's 0% coverage. It explains that 'filename' refers to a CSV file, 'columns' can be a single column name or list, 'ascending' controls sort direction, and 'limit' optionally restricts row count. This adds substantial value over the bare schema, though it doesn't cover edge cases like column name validation or limit behavior with null values.

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 as 'Sort CSV data by specified columns' which is a specific verb (sort) + resource (CSV data) + operation (by columns). It distinguishes from siblings like filter_data or group_data by focusing on sorting rather than filtering or grouping operations. However, it doesn't explicitly contrast with all similar siblings.

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 filter_data, group_data, and read_csv that might overlap in data manipulation contexts, there's no indication of when sorting is preferred over other operations or what prerequisites might exist for using this tool.

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