Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

get_value_counts

Count unique values in a CSV column to analyze data distribution and identify patterns.

Instructions

Get value counts for a column.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
columnYes
normalizeNo
sortNo
ascendingNo
top_nNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core implementation of get_value_counts tool: retrieves DataFrame from session, computes value counts with options for normalization, sorting, and top_n, converts to dictionary format, adds statistics, and handles errors.
    async def get_value_counts(
        session_id: str,
        column: str,
        normalize: bool = False,
        sort: bool = True,
        ascending: bool = False,
        top_n: Optional[int] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Get value counts for a column.
        
        Args:
            session_id: Session identifier
            column: Column name to count values
            normalize: Return proportions instead of counts
            sort: Sort by frequency
            ascending: Sort order
            top_n: Return only top N values
            ctx: FastMCP context
            
        Returns:
            Dict with value counts
        """
        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
            
            if column not in df.columns:
                return {"success": False, "error": f"Column '{column}' not found"}
            
            # Get value counts
            value_counts = df[column].value_counts(
                normalize=normalize,
                sort=sort,
                ascending=ascending,
                dropna=False
            )
            
            # Apply top_n if specified
            if top_n:
                value_counts = value_counts.head(top_n)
            
            # Convert to dict
            counts_dict = {}
            for value, count in value_counts.items():
                key = str(value) if not pd.isna(value) else "NaN"
                counts_dict[key] = float(count) if normalize else int(count)
            
            # Calculate additional statistics
            unique_count = df[column].nunique(dropna=False)
            null_count = df[column].isna().sum()
            
            session.record_operation(OperationType.ANALYZE, {
                "type": "value_counts",
                "column": column,
                "normalize": normalize,
                "top_n": top_n
            })
            
            return {
                "success": True,
                "column": column,
                "value_counts": counts_dict,
                "unique_values": int(unique_count),
                "null_count": int(null_count),
                "total_count": len(df),
                "normalized": normalize
            }
            
        except Exception as e:
            logger.error(f"Error getting value counts: {str(e)}")
            return {"success": False, "error": str(e)}
  • Registers the get_value_counts tool using @mcp.tool decorator, providing the tool interface and delegating execution to the imported implementation.
    async def get_value_counts(
        session_id: str,
        column: str,
        normalize: bool = False,
        sort: bool = True,
        ascending: bool = False,
        top_n: Optional[int] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Get value counts for a column."""
        return await _get_value_counts(session_id, column, normalize, sort, ascending, top_n, ctx)
Behavior2/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 states 'Get value counts' but doesn't clarify if this is a read-only operation, what the output format is (though an output schema exists), or any side effects like performance impacts. For a tool with 6 parameters and no annotation coverage, this leaves significant gaps in understanding its behavior and constraints.

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 a single, efficient sentence with no wasted words. It's front-loaded with the core action ('Get value counts'), making it easy to scan. Every part of the sentence contributes directly to the purpose, achieving high conciseness without under-specification in terms of length.

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's moderate complexity (6 parameters, 2 required) and the presence of an output schema (which handles return values), the description is minimally adequate. However, with no annotations and 0% schema description coverage, it lacks details on behavioral traits and parameter meanings, making it incomplete for full contextual understanding. It meets a baseline but has 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%, meaning none of the 6 parameters are documented in the schema. The description only mentions 'a column', implicitly referring to the 'column' parameter, but doesn't explain the purpose of other parameters like 'session_id', 'normalize', 'sort', 'ascending', or 'top_n'. This fails to compensate for the low coverage, leaving most 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 'Get value counts for a column' clearly states the verb ('Get') and resource ('value counts for a column'), making the purpose understandable. However, it lacks specificity about what 'value counts' entails (e.g., frequency distribution) and doesn't differentiate from siblings like 'get_column_statistics' or 'profile_data', which might offer overlapping functionality. This makes it vague in distinguishing its unique role.

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. It doesn't mention prerequisites (e.g., needing an active session), exclusions, or comparisons to siblings like 'get_column_statistics' for broader stats or 'profile_data' for comprehensive analysis. Without such context, an agent might struggle to select this tool appropriately in a workflow.

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