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
| Name | Required | Description | Default |
|---|---|---|---|
| filename | Yes | ||
| columns | Yes | ||
| ascending | No | ||
| limit | No |
Implementation Reference
- csv_mcp_server/csv_manager.py:411-448 (handler)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
- csv_mcp_server/server.py:205-228 (registration)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)}