Skip to main content
Glama
K02D

MCP Tabular Data Analysis Server

by K02D

create_pivot_table

Generate pivot tables from CSV or SQLite data to summarize and analyze business metrics by grouping rows and columns with customizable aggregation functions.

Instructions

Create a pivot table from tabular data - the most common business analysis operation.

Args:
    file_path: Path to CSV or SQLite file
    index: Column(s) to use as row labels (grouping)
    columns: Column(s) to use as column headers (optional)
    values: Column to aggregate (default: first numeric column)
    aggfunc: Aggregation function - 'sum', 'mean', 'count', 'min', 'max', 'median', 'std'
    fill_value: Value to replace missing entries (default: None = show as null)

Returns:
    Dictionary containing the pivot table data and metadata

Example:
    create_pivot_table(
        file_path="data/sales.csv",
        index=["region"],
        columns=["category"],
        values="revenue",
        aggfunc="sum"
    )

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
indexYes
columnsNo
valuesNo
aggfuncNomean
fill_valueNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler function for the 'create_pivot_table' MCP tool. It loads data using _load_data, validates parameters, creates a pandas pivot table, and returns structured results including the pivot data and summary statistics.
    def create_pivot_table(
        file_path: str,
        index: list[str],
        columns: list[str] | None = None,
        values: str | None = None,
        aggfunc: str = "mean",
        fill_value: float | None = None,
    ) -> dict[str, Any]:
        """
        Create a pivot table from tabular data - the most common business analysis operation.
        
        Args:
            file_path: Path to CSV or SQLite file
            index: Column(s) to use as row labels (grouping)
            columns: Column(s) to use as column headers (optional)
            values: Column to aggregate (default: first numeric column)
            aggfunc: Aggregation function - 'sum', 'mean', 'count', 'min', 'max', 'median', 'std'
            fill_value: Value to replace missing entries (default: None = show as null)
        
        Returns:
            Dictionary containing the pivot table data and metadata
        
        Example:
            create_pivot_table(
                file_path="data/sales.csv",
                index=["region"],
                columns=["category"],
                values="revenue",
                aggfunc="sum"
            )
        """
        df = _load_data(file_path)
        
        # Validate index columns
        invalid = [c for c in index if c not in df.columns]
        if invalid:
            raise ValueError(f"Index columns not found: {invalid}. Available: {df.columns.tolist()}")
        
        # Validate columns if provided
        if columns:
            invalid = [c for c in columns if c not in df.columns]
            if invalid:
                raise ValueError(f"Column headers not found: {invalid}")
        
        # Default to first numeric column if values not specified
        if values is None:
            numeric_cols = _get_numeric_columns(df)
            if not numeric_cols:
                raise ValueError("No numeric columns found for aggregation")
            values = numeric_cols[0]
        elif values not in df.columns:
            raise ValueError(f"Values column '{values}' not found")
        
        # Map aggfunc string to function
        agg_map = {
            "sum": "sum",
            "mean": "mean",
            "count": "count",
            "min": "min",
            "max": "max",
            "median": "median",
            "std": "std",
        }
        if aggfunc not in agg_map:
            raise ValueError(f"Unknown aggfunc: {aggfunc}. Use: {list(agg_map.keys())}")
        
        # Create pivot table
        pivot = pd.pivot_table(
            df,
            values=values,
            index=index,
            columns=columns,
            aggfunc=agg_map[aggfunc],
            fill_value=fill_value,
        )
        
        # Reset index for cleaner output
        pivot_reset = pivot.reset_index()
        
        return {
            "index": index,
            "columns": columns,
            "values": values,
            "aggfunc": aggfunc,
            "shape": {"rows": len(pivot), "columns": len(pivot.columns)},
            "pivot_table": pivot_reset.to_dict(orient="records"),
            "summary": {
                "total": float(pivot.values.sum()) if np.issubdtype(pivot.values.dtype, np.number) else None,
                "grand_mean": float(pivot.values.mean()) if np.issubdtype(pivot.values.dtype, np.number) else None,
            }
        }
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the core operation (creating a pivot table) and mentions the return format ('dictionary containing the pivot table data and metadata'), but doesn't cover important behavioral aspects like error handling, performance characteristics, file format limitations beyond CSV/SQLite, or whether the operation modifies source data.

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, follows with detailed parameter explanations in a structured format, specifies the return value, and provides a concrete example. Every sentence adds value without redundancy, making it easy for an AI agent to parse and understand.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

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

Given the tool's complexity (6 parameters, data transformation operation) and the presence of an output schema, the description is largely complete. It explains the core operation, all parameters, and mentions the return format. The main gap is lack of behavioral context around errors, performance, or limitations, but the output schema reduces the need to fully describe return values.

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

Parameters5/5

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

With 0% schema description coverage, the description provides excellent parameter semantics that fully compensate. Each parameter is clearly explained with its purpose, defaults, and examples. The description adds substantial meaning beyond the bare schema, explaining what 'index', 'columns', 'values', 'aggfunc', and 'fill_value' actually mean in the context of pivot table creation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 with specific verbs ('create a pivot table from tabular data') and resource ('tabular data'), distinguishing it from sibling tools like 'group_aggregate' or 'analyze_time_series'. It explicitly identifies this as 'the most common business analysis operation', providing clear differentiation.

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 'group_aggregate' or 'analyze_time_series'. While it mentions this is for 'the most common business analysis operation', it doesn't specify scenarios where pivot tables are preferred over other aggregation or analysis methods available in the sibling tools.

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/K02D/mcp-tabular'

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