Skip to main content
Glama

extract_from_column

Extract specific patterns from CSV columns using regex capturing groups. Parse email addresses, product codes, names, dates, and other structured data into separate columns for analysis.

Instructions

Extract patterns from a column using regex with capturing groups.

Returns: ColumnOperationResult with extraction details

Examples: # Extract email parts extract_from_column(ctx, "email", r"(.+)@(.+)")

# Extract code components
extract_from_column(ctx, "product_code", r"([A-Z]{2})-(\d+)")

# Extract and expand into multiple columns
extract_from_column(ctx, "full_name", r"(\w+)\s+(\w+)", expand=True)

# Extract year from date string
extract_from_column(ctx, "date", r"\d{4}")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
columnYesColumn name to extract patterns from
patternYesRegex pattern with capturing groups to extract
expandYesWhether to expand multiple groups into separate columns

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 async handler function implementing the 'extract_from_column' tool. It validates the regex pattern, extracts matches from the specified column using pandas str.extract, optionally expands capturing groups into new columns, and returns a ColumnOperationResult.
    async def extract_from_column(
        ctx: Annotated[Context, Field(description="FastMCP context for session access")],
        column: Annotated[str, Field(description="Column name to extract patterns from")],
        pattern: Annotated[str, Field(description="Regex pattern with capturing groups to extract")],
        *,
        expand: Annotated[
            bool,
            Field(description="Whether to expand multiple groups into separate columns"),
        ] = False,
    ) -> ColumnOperationResult:
        r"""Extract patterns from a column using regex with capturing groups.
    
        Returns:
            ColumnOperationResult with extraction details
    
        Examples:
            # Extract email parts
            extract_from_column(ctx, "email", r"(.+)@(.+)")
    
            # Extract code components
            extract_from_column(ctx, "product_code", r"([A-Z]{2})-(\d+)")
    
            # Extract and expand into multiple columns
            extract_from_column(ctx, "full_name", r"(\w+)\s+(\w+)", expand=True)
    
            # Extract year from date string
            extract_from_column(ctx, "date", r"\d{4}")
    
        """
        # Get session_id from FastMCP context
        session_id = ctx.session_id
        _session, df = get_session_data(session_id)
    
        _validate_column_exists(column, df)
    
        # Validate regex pattern
        try:
            re.compile(pattern)
        except re.error as e:
            msg = "pattern"
            raise InvalidParameterError(msg, pattern, f"Invalid regex pattern: {e}") from e
    
        # Apply extraction
        # pandas typing limitation: str.extract(expand=bool) overload not properly typed in pandas-stubs
        # See: https://github.com/pandas-dev/pandas-stubs/issues/43
        extracted = df[column].astype(str).str.extract(pattern, expand=expand)  # type: ignore[call-overload]
    
        if expand and isinstance(extracted, pd.DataFrame):
            # Multiple capturing groups - create new columns
            columns_created = []
            for i in range(len(extracted.columns)):
                new_col_name = f"{column}_extracted_{i}"
                df[new_col_name] = extracted.iloc[:, i]
                columns_created.append(new_col_name)
    
            affected_columns = columns_created
            operation_desc = f"extract_expand_{len(columns_created)}_groups"
        else:
            # Single group or no expand - replace original column
            if isinstance(extracted, pd.DataFrame):
                # Multiple groups but not expanding - take first group
                df[column] = extracted.iloc[:, 0]
            else:
                # Single series result
                df[column] = extracted
    
            affected_columns = [column]
            operation_desc = "extract_pattern"
    
        # Count successful extractions (non-null results)
        if expand and isinstance(extracted, pd.DataFrame):
            successful_extractions = int((~extracted.isna()).any(axis=1).sum())
        else:
            successful_extractions = (
                int(extracted.notna().sum()) if hasattr(extracted, "notna") else len(extracted)
            )
    
        return ColumnOperationResult(
            operation=operation_desc,
            rows_affected=successful_extractions,
            columns_affected=affected_columns,
        )
  • Registers the extract_from_column handler as a FastMCP tool named 'extract_from_column' on the column_text_server instance.
    column_text_server.tool(name="extract_from_column")(extract_from_column)
  • Pydantic schema definitions for tool parameters via Annotated types and Field descriptions.
    async def extract_from_column(
        ctx: Annotated[Context, Field(description="FastMCP context for session access")],
        column: Annotated[str, Field(description="Column name to extract patterns from")],
        pattern: Annotated[str, Field(description="Regex pattern with capturing groups to extract")],
        *,
        expand: Annotated[
            bool,
            Field(description="Whether to expand multiple groups into separate columns"),
        ] = False,
    ) -> ColumnOperationResult:
Behavior2/5

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

With no annotations provided, the description carries full burden but only partially discloses behavior. It mentions the return type ('ColumnOperationResult with extraction details') and shows examples of regex usage, but omits critical details like error handling, performance implications, or whether the operation modifies the original dataset versus creating a new one.

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, followed by useful examples. However, the examples section is lengthy relative to the explanatory text, slightly reducing efficiency.

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 moderate complexity (regex operations), 100% schema coverage, and presence of an output schema (implied by 'Returns: ColumnOperationResult'), the description is mostly complete. It covers purpose and examples well, but could better address behavioral aspects like mutability or error cases.

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?

Schema description coverage is 100%, so the baseline is 3. The description adds minimal value beyond the schema by illustrating parameter usage in examples (e.g., 'expand=True' for multiple columns), but doesn't provide additional semantic context like regex pattern validation or column existence requirements.

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 specific action ('extract patterns from a column using regex with capturing groups'), identifies the resource ('a column'), and distinguishes it from sibling tools like 'split_column' or 'replace_in_column' by focusing on regex-based extraction rather than other column operations.

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 provides implied usage through examples (e.g., extracting email parts, code components, names), but lacks explicit guidance on when to use this tool versus alternatives like 'split_column' or 'replace_in_column'. 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