Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

sort_data

Sort CSV data by specified columns to organize information for analysis or presentation.

Instructions

Sort data by columns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
columnsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that implements the sorting logic using pandas DataFrame.sort_values, parses column specifications, validates columns, updates the session dataframe, and records the operation.
    async def sort_data(
        session_id: str, 
        columns: List[Union[str, Dict[str, str]]], 
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Sort data by one or more columns.
        
        Args:
            session_id: Session identifier
            columns: List of column names or dicts with 'column' and 'ascending' keys
            ctx: FastMCP context
            
        Returns:
            Dict with success status
        """
        try:
            manager = get_session_manager()
            session = manager.get_session(session_id)
            
            if not session or session.df is None:
                return {"success": False, "error": "Invalid session or no data loaded"}
            
            df = session.df
            
            # Parse columns into names and ascending flags
            sort_columns = []
            ascending = []
            
            for col in columns:
                if isinstance(col, str):
                    sort_columns.append(col)
                    ascending.append(True)
                elif isinstance(col, dict):
                    sort_columns.append(col["column"])
                    ascending.append(col.get("ascending", True))
                else:
                    return {"success": False, "error": f"Invalid column specification: {col}"}
            
            # Validate columns exist
            for col in sort_columns:
                if col not in df.columns:
                    return {"success": False, "error": f"Column '{col}' not found"}
            
            session.df = df.sort_values(by=sort_columns, ascending=ascending).reset_index(drop=True)
            session.record_operation(OperationType.SORT, {
                "columns": sort_columns,
                "ascending": ascending
            })
            
            return {
                "success": True,
                "sorted_by": sort_columns,
                "ascending": ascending
            }
            
        except Exception as e:
            logger.error(f"Error sorting data: {str(e)}")
            return {"success": False, "error": str(e)}
  • MCP tool registration decorator (@mcp.tool) and wrapper function that delegates to the core _sort_data implementation from transformations module.
    @mcp.tool
    async def sort_data(
        session_id: str,
        columns: List[Any],
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Sort data by columns."""
        return await _sort_data(session_id, columns, ctx)
Behavior2/5

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

With no annotations, the description carries full burden but only states the basic action. It doesn't disclose behavioral traits such as whether sorting is in-place or returns a new dataset, if it affects session state, performance implications, or error handling. This is a significant gap for a mutation tool with zero annotation coverage.

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 extremely concise with a single sentence, 'Sort data by columns.', which is front-loaded and wastes no words. It efficiently conveys the core purpose without unnecessary elaboration, though this brevity contributes to gaps in other dimensions.

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 the tool has an output schema (which likely describes the sorted result), the description doesn't need to explain return values. However, with 2 parameters at 0% schema coverage and no annotations, the description is incomplete—it lacks context on session management, data mutability, and parameter usage, making it minimally adequate but with clear gaps.

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

Parameters2/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 but adds no parameter details. It doesn't explain what 'session_id' refers to (e.g., an active data session) or the format of 'columns' (e.g., array of column names with optional sort order). The description fails to provide meaning beyond the bare schema.

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 'Sort data by columns' clearly states the action (sort) and target (data), but it's vague about what 'data' refers to (likely a dataset in a session) and doesn't distinguish from siblings like 'group_by_aggregate' or 'select_columns' that also manipulate data columns. It avoids tautology but lacks specificity.

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 is provided on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing an active session with data loaded), exclusions, or related tools like 'filter_rows' or 'group_by_aggregate' for different data manipulations. The description alone offers no usage context.

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/santoshray02/csv-editor'

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