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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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()}"
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. The description mentions that it 'returns information about the sorted data' but doesn't specify what that information includes (e.g., success/failure, row count, file path). It also doesn't mention potential side effects like file creation when output_path is provided, error conditions, or performance characteristics. For a tool with 4 parameters and no annotations, this is insufficient behavioral context.

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 appropriately sized. It begins with a clear purpose statement, then provides an organized Args section with bullet-like formatting, and concludes with a Returns statement. Every sentence earns its place, with no redundant information. 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 parameters but lacks important context. There's an output schema (indicated by 'Has output schema: true'), so the description doesn't need to detail return values. However, for a data manipulation tool with siblings, it should provide more guidance on usage context and behavioral expectations. The parameter explanations are good, but overall completeness is only adequate.

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?

Schema description coverage is 0%, so the description must compensate. The Args section provides clear explanations for all 4 parameters: file_path, column, descending, and output_path. Each parameter's purpose is explained, including the default for 'descending' and optional nature of 'output_path'. This adds significant value beyond the bare schema, though it doesn't specify file format requirements or column validation rules.

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: 'Sort data by a specific column.' This specifies the verb ('sort') and resource ('data'), but it doesn't distinguish this tool from sibling tools like 'filter_data' or 'analyze_data' beyond the sorting action. The title is null, so the description carries the full burden of purpose definition.

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 sibling tools like 'filter_data', 'analyze_data', and 'convert_data', there's no indication of when sorting is appropriate versus other data manipulation operations. The description only states what the tool does, not when it should be selected.

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