Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

group_by_aggregate

Group CSV data by specified columns and apply aggregation functions to analyze and summarize information from large datasets.

Instructions

Group data and apply aggregation functions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
group_byYes
aggregationsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that performs the groupby aggregation logic using pandas groupby. Validates inputs, executes groupby.agg, flattens multiindex columns, stores result in session, records operation.
    async def group_by_aggregate(
        session_id: str,
        group_by: List[str],
        aggregations: Dict[str, Union[str, List[str]]],
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Group data and apply aggregation functions.
        
        Args:
            session_id: Session identifier
            group_by: Columns to group by
            aggregations: Dict mapping column names to aggregation functions
                         e.g., {"sales": ["sum", "mean"], "quantity": "sum"}
            ctx: FastMCP context
            
        Returns:
            Dict with grouped data
        """
        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
            
            # Validate group by columns
            missing_cols = [col for col in group_by if col not in df.columns]
            if missing_cols:
                return {"success": False, "error": f"Group by columns not found: {missing_cols}"}
            
            # Validate aggregation columns
            agg_cols = list(aggregations.keys())
            missing_agg_cols = [col for col in agg_cols if col not in df.columns]
            if missing_agg_cols:
                return {"success": False, "error": f"Aggregation columns not found: {missing_agg_cols}"}
            
            # Prepare aggregation dict
            agg_dict = {}
            for col, funcs in aggregations.items():
                if isinstance(funcs, str):
                    agg_dict[col] = [funcs]
                else:
                    agg_dict[col] = funcs
            
            # Perform groupby
            grouped = df.groupby(group_by).agg(agg_dict)
            
            # Flatten column names
            grouped.columns = ['_'.join(col).strip() if col[1] else col[0] 
                              for col in grouped.columns.values]
            
            # Reset index to make group columns regular columns
            result_df = grouped.reset_index()
            
            # Convert to dict for response
            result = {
                "data": result_df.to_dict(orient='records'),
                "shape": {
                    "rows": len(result_df),
                    "columns": len(result_df.columns)
                },
                "columns": result_df.columns.tolist()
            }
            
            # Store grouped data in session
            session.df = result_df
            session.record_operation(OperationType.GROUP_BY, {
                "group_by": group_by,
                "aggregations": aggregations,
                "result_shape": result["shape"]
            })
            
            return {
                "success": True,
                "grouped_data": result,
                "group_by": group_by,
                "aggregations": aggregations
            }
            
        except Exception as e:
            logger.error(f"Error in group by aggregate: {str(e)}")
            return {"success": False, "error": str(e)}
  • MCP tool registration with @mcp.tool decorator. Wrapper function that delegates to the core implementation in analytics.py.
    @mcp.tool
    async def group_by_aggregate(
        session_id: str,
        group_by: List[str],
        aggregations: Dict[str, Any],
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Group data and apply aggregation functions."""
        return await _group_by_aggregate(session_id, group_by, aggregations, ctx)
Behavior1/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It only states what the tool does ('group data and apply aggregation functions') without mentioning any behavioral traits such as whether it modifies data in-place, requires specific permissions, has side effects, or how it handles errors. This is inadequate for a tool with three parameters and no 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 ('Group data and apply aggregation functions.'), which is front-loaded and wastes no words. It efficiently conveys the core action, 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.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (3 parameters, nested objects, no annotations, but with an output schema), the description is incomplete. It doesn't address parameter meanings, usage context, or behavioral aspects. While the output schema might cover return values, the description lacks essential details for proper tool invocation and understanding.

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

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage, meaning parameters 'session_id', 'group_by', and 'aggregations' are undocumented in the schema. The description adds no meaning beyond the schema—it doesn't explain what these parameters represent, their formats, or examples of use. With low schema coverage, the description fails to compensate, leaving parameters semantically unclear.

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 'Group data and apply aggregation functions' clearly states the tool's purpose with a specific verb ('group') and resource ('data'), but it doesn't differentiate this from sibling tools like 'get_value_counts' or 'get_column_statistics' which might perform similar aggregation operations. The purpose is understandable but lacks sibling distinction.

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 like 'get_value_counts' or 'get_column_statistics'. It doesn't mention prerequisites (e.g., needing an active session) or context for when grouping and aggregation are appropriate, leaving the agent with no usage direction.

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