Skip to main content
Glama

pivot_table

Create pivot tables from Excel data to summarize and analyze information by grouping, aggregating, and restructuring datasets for clearer insights.

Instructions

Create a pivot table from Excel data.

Args:
    file_path: Path to the Excel file
    index: Column to use as the pivot table index
    columns: Optional column to use as the pivot table columns
    values: Column to use as the pivot table values
    aggfunc: Aggregation function ('mean', 'sum', 'count', etc.)
    sheet_name: Name of the sheet to pivot (for Excel files)
    
Returns:
    Pivot table as string

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
indexYes
columnsNo
valuesNo
aggfuncNomean
sheet_nameNo

Implementation Reference

  • The main handler function for the 'pivot_table' tool. Decorated with @mcp.tool() which registers it as an MCP tool. Reads the Excel/CSV file, prepares pivot table parameters based on inputs, maps aggregation function strings to numpy/pandas functions, creates the pivot table using pd.pivot_table, and returns it as a formatted string.
    @mcp.tool()
    def pivot_table(file_path: str, index: str, columns: Optional[str] = None, 
                  values: str = None, aggfunc: str = "mean", 
                  sheet_name: Optional[str] = None) -> str:
        """
        Create a pivot table from Excel data.
        
        Args:
            file_path: Path to the Excel file
            index: Column to use as the pivot table index
            columns: Optional column to use as the pivot table columns
            values: Column to use as the pivot table values
            aggfunc: Aggregation function ('mean', 'sum', 'count', etc.)
            sheet_name: Name of the sheet to pivot (for Excel files)
            
        Returns:
            Pivot table as string
        """
        try:
            # Read file
            _, ext = os.path.splitext(file_path)
            ext = ext.lower()
            
            read_params = {}
            if ext in ['.xlsx', '.xls', '.xlsm'] and sheet_name is not None:
                read_params["sheet_name"] = sheet_name
                
            if ext in ['.xlsx', '.xls', '.xlsm']:
                df = pd.read_excel(file_path, **read_params)
            elif ext == '.csv':
                df = pd.read_csv(file_path)
            elif ext == '.tsv':
                df = pd.read_csv(file_path, sep='\t')
            elif ext == '.json':
                df = pd.read_json(file_path)
            else:
                return f"Unsupported file extension: {ext}"
            
            # Configure pivot table params
            pivot_params = {"index": index}
            if columns:
                pivot_params["columns"] = columns
            if values:
                pivot_params["values"] = values
                
            # Map string aggfunc to actual function
            if aggfunc == "mean":
                pivot_params["aggfunc"] = np.mean
            elif aggfunc == "sum":
                pivot_params["aggfunc"] = np.sum
            elif aggfunc == "count":
                pivot_params["aggfunc"] = len
            elif aggfunc == "min":
                pivot_params["aggfunc"] = np.min
            elif aggfunc == "max":
                pivot_params["aggfunc"] = np.max
            else:
                return f"Unsupported aggregation function: {aggfunc}"
            
            # Create pivot table
            pivot = pd.pivot_table(df, **pivot_params)
            
            return pivot.to_string()
        except Exception as e:
            return f"Error creating pivot table: {str(e)}"
  • The @mcp.tool() decorator on the pivot_table function serves as the registration mechanism in FastMCP, automatically registering the function as a tool named 'pivot_table' based on its definition.
    @mcp.tool()
  • The function signature and docstring define the input schema (parameters with types and descriptions) and output schema for the pivot_table tool.
    def pivot_table(file_path: str, index: str, columns: Optional[str] = None, 
                  values: str = None, aggfunc: str = "mean", 
                  sheet_name: Optional[str] = None) -> str:
        """
        Create a pivot table from Excel data.
        
        Args:
            file_path: Path to the Excel file
            index: Column to use as the pivot table index
            columns: Optional column to use as the pivot table columns
            values: Column to use as the pivot table values
            aggfunc: Aggregation function ('mean', 'sum', 'count', etc.)
            sheet_name: Name of the sheet to pivot (for Excel files)
            
        Returns:
            Pivot table as string
        """
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the tool creates a pivot table and returns it as a string, but lacks details on permissions needed, file format requirements, error handling, or performance characteristics. The description is minimal beyond basic functionality.

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, followed by a parameter list with brief explanations, and ends with return information. Every sentence serves a clear purpose with zero wasted content.

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 6 parameters with no schema descriptions and no output schema, the description provides parameter semantics but lacks behavioral context. For a data transformation tool with multiple siblings, it should ideally explain more about when to use it, what the output format entails, or any limitations. It's minimally adequate but has clear gaps.

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?

The description provides clear semantic explanations for all 6 parameters beyond their titles in the schema (which has 0% description coverage). Each parameter's role in pivot table creation is explained, such as 'index: Column to use as the pivot table index' and 'aggfunc: Aggregation function ('mean', 'sum', 'count', etc.)'. This adds significant value over the bare schema.

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 creates a pivot table from Excel data, specifying the verb 'create' and resource 'pivot table from Excel data'. It distinguishes from siblings like 'analyze_excel' or 'data_summary' by focusing specifically on pivot table creation, though it doesn't explicitly contrast with them.

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 like 'analyze_excel' or 'data_summary'. The description only states what the tool does without indicating appropriate contexts, prerequisites, or exclusions.

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/yzfly/mcp-excel-server'

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