Skip to main content
Glama

sort_data

Sort data files by specific columns to organize information for analysis. Specify ascending or descending order and optionally save sorted results.

Instructions

Sort data by a specific column.

Args: file_path: Path to the data file column: Column name to sort by descending: Sort in descending order (default: False) output_path: Optional path to save sorted data

Returns: Information about the sorted data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
columnYes
descendingNo
output_pathNo

Implementation Reference

  • The sort_data tool implementation registered with @mcp.tool() decorator. This function loads data using pandas, sorts it by a specified column in ascending or descending order, optionally saves the sorted data to an output file, and returns sorting information as JSON.
    @mcp.tool()
    def sort_data(file_path: str, column: str, descending: bool = False, output_path: Optional[str] = None) -> str:
        """
        Sort data by a specific column.
        
        Args:
            file_path: Path to the data file
            column: Column name to sort by
            descending: Sort in descending order (default: False)
            output_path: Optional path to save sorted data
        
        Returns:
            Information about the sorted 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)}"
            
            # Sort the data
            sorted_df = df.sort_values(by=column, ascending=not descending)
            
            result = {
                "sorted_by": column,
                "descending": descending,
                "total_rows": len(sorted_df)
            }
            
            # If output path is specified, save sorted data
            if output_path:
                output_extension = Path(output_path).suffix.lower()
                if output_extension == '.csv':
                    sorted_df.to_csv(output_path, index=False)
                elif output_extension == '.json':
                    sorted_df.to_json(output_path, orient='records', indent=2)
                elif output_extension in ['.xlsx', '.xls']:
                    sorted_df.to_excel(output_path, index=False)
                else:
                    # Default to CSV
                    sorted_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 sorting data: {str(e)}\n{traceback.format_exc()}"

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