Skip to main content
Glama

remove_duplicates

Eliminate duplicate rows from dataframes with flexible column selection and keep strategies. Provides validation and statistics for data cleaning.

Instructions

Remove duplicate rows from the dataframe with comprehensive validation.

Provides flexible duplicate removal with options for column subset selection and different keep strategies. Handles edge cases and provides detailed statistics about the deduplication process.

Examples: # Remove exact duplicate rows remove_duplicates(ctx)

# Remove duplicates based on specific columns
remove_duplicates(ctx, subset=["email", "name"])

# Keep last occurrence instead of first
remove_duplicates(ctx, subset=["id"], keep="last")

# Remove all duplicates (keep none)
remove_duplicates(ctx, subset=["email"], keep="none")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subsetNoColumns to consider for duplicates (None = all columns)
keepNoWhich duplicates to keep: first, last, or nonefirst

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
successNoWhether operation completed successfully
operationYesType of operation performed
transformNoTransform description
part_indexNoPart index for split operations
nulls_filledNoNumber of null values filled
rows_removedNoNumber of rows removed (for remove_duplicates)
rows_affectedYesNumber of rows affected by operation
values_filledNoNumber of values filled (for fill_missing_values)
updated_sampleNoSample values after operation
original_sampleNoSample values before operation
columns_affectedYesNames of columns affected

Implementation Reference

  • The main handler function that implements the remove_duplicates tool logic using pandas drop_duplicates on the session dataframe, with parameters for subset columns and keep strategy, returning a ColumnOperationResult.
    def remove_duplicates(
        ctx: Annotated[Context, Field(description="FastMCP context for session access")],
        subset: Annotated[
            list[str] | None,
            Field(description="Columns to consider for duplicates (None = all columns)"),
        ] = None,
        keep: Annotated[
            Literal["first", "last", "none"],
            Field(description="Which duplicates to keep: first, last, or none"),
        ] = "first",
    ) -> ColumnOperationResult:
        """Remove duplicate rows from the dataframe with comprehensive validation.
    
        Provides flexible duplicate removal with options for column subset selection
        and different keep strategies. Handles edge cases and provides detailed
        statistics about the deduplication process.
    
        Examples:
            # Remove exact duplicate rows
            remove_duplicates(ctx)
    
            # Remove duplicates based on specific columns
            remove_duplicates(ctx, subset=["email", "name"])
    
            # Keep last occurrence instead of first
            remove_duplicates(ctx, subset=["id"], keep="last")
    
            # Remove all duplicates (keep none)
            remove_duplicates(ctx, subset=["email"], keep="none")
    
        """
        session_id = ctx.session_id
        session, df = get_session_data(session_id)
        rows_before = len(df)
    
        # Validate subset columns if provided
        if subset:
            missing_cols = [col for col in subset if col not in df.columns]
            if missing_cols:
                msg = f"Columns not found in subset: {missing_cols}"
                raise ToolError(msg)
    
        # Convert keep parameter for pandas
        keep_param: Literal["first", "last"] | Literal[False] = keep if keep != "none" else False
    
        # Remove duplicates
        session.df = df.drop_duplicates(subset=subset, keep=keep_param).reset_index(drop=True)
    
        rows_after = len(session.df)
        rows_removed = rows_before - rows_after
    
        # No longer recording operations (simplified MCP architecture)
    
        return ColumnOperationResult(
            operation="remove_duplicates",
            rows_affected=rows_after,
            columns_affected=subset if subset else df.columns.tolist(),
            rows_removed=rows_removed,
        )
  • Registers the remove_duplicates function as an MCP tool on the transformation_server.
    transformation_server.tool(name="remove_duplicates")(remove_duplicates)
  • Pydantic response model used by remove_duplicates (ColumnOperationResult), includes specific field rows_removed for this operation.
    class ColumnOperationResult(BaseToolResponse):
        """Response model for column operations (add, remove, rename, etc.)."""
    
        operation: str = Field(description="Type of operation performed")
        rows_affected: int = Field(description="Number of rows affected by operation")
        columns_affected: list[str] = Field(description="Names of columns affected")
        original_sample: list[CsvCellValue] | None = Field(
            default=None,
            description="Sample values before operation",
        )
        updated_sample: list[CsvCellValue] | None = Field(
            default=None,
            description="Sample values after operation",
        )
        # Additional fields for specific operations
        part_index: int | None = Field(default=None, description="Part index for split operations")
        transform: str | None = Field(default=None, description="Transform description")
        nulls_filled: int | None = Field(default=None, description="Number of null values filled")
        rows_removed: int | None = Field(
            default=None,
            description="Number of rows removed (for remove_duplicates)",
        )
        values_filled: int | None = Field(
            default=None,
            description="Number of values filled (for fill_missing_values)",
        )
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. It mentions 'comprehensive validation,' 'handles edge cases,' and 'provides detailed statistics,' which adds some behavioral context beyond the basic operation. However, it does not detail permissions, side effects, or error handling, leaving gaps for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the core purpose. The examples are helpful but could be more concise; overall, most sentences earn their place by illustrating flexibility, though some redundancy exists with the schema.

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 (mutation with parameters), no annotations, but a rich input schema (100% coverage) and an output schema (implied by context signals), the description is fairly complete. It covers purpose, flexibility, and examples, though more behavioral details would enhance it.

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

Parameters3/5

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

The input schema has 100% description coverage, clearly documenting 'subset' and 'keep' parameters. The description adds minimal value beyond the schema, as examples illustrate usage but do not provide additional semantic meaning. This meets the baseline for high schema coverage.

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's purpose: 'Remove duplicate rows from the dataframe with comprehensive validation.' It specifies the verb ('remove'), resource ('duplicate rows'), and context ('dataframe'), but does not explicitly differentiate from sibling tools like 'filter_rows' or 'delete_row' which might also affect row selection.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage through examples (e.g., removing exact duplicates vs. based on columns), but lacks explicit guidance on when to use this tool versus alternatives like 'filter_rows' for general row selection or 'delete_row' for targeted removal. No exclusions or prerequisites are mentioned.

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/jonpspri/databeak'

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