Skip to main content
Glama

validate_formula_syntax

Check Excel formula syntax for correctness before applying it. Input file path, sheet name, cell, and formula to ensure accurate syntax validation without execution.

Instructions

Validate Excel formula syntax without applying it.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cellYes
filepathYes
formulaYes
sheet_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler and registration for the 'validate_formula_syntax' MCP tool. It processes inputs, resolves file paths, calls the validation helper, and returns results or errors.
    @mcp.tool()
    def validate_formula_syntax(
        filepath: str,
        sheet_name: str,
        cell: str,
        formula: str,
    ) -> str:
        """Validate Excel formula syntax without applying it."""
        try:
            full_path = get_excel_path(filepath)
            result = validate_formula_impl(full_path, sheet_name, cell, formula)
            return result["message"]
        except (ValidationError, CalculationError) as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error validating formula: {e}")
            raise
  • Core helper function (validate_formula_in_cell_operation, imported as validate_formula_impl) that performs detailed formula syntax validation, cell reference checks, workbook loading, and comparison with existing cell content.
    def validate_formula_in_cell_operation(
        filepath: str,
        sheet_name: str,
        cell: str,
        formula: str
    ) -> dict[str, Any]:
        """Validate Excel formula before writing"""
        try:
            wb = load_workbook(filepath)
            if sheet_name not in wb.sheetnames:
                raise ValidationError(f"Sheet '{sheet_name}' not found")
    
            if not validate_cell_reference(cell):
                raise ValidationError(f"Invalid cell reference: {cell}")
    
            # First validate the provided formula's syntax
            is_valid, message = validate_formula(formula)
            if not is_valid:
                raise ValidationError(f"Invalid formula syntax: {message}")
    
            # Additional validation for cell references in formula
            cell_refs = re.findall(r'[A-Z]+[0-9]+(?::[A-Z]+[0-9]+)?', formula)
            for ref in cell_refs:
                if ':' in ref:  # Range reference
                    start, end = ref.split(':')
                    if not (validate_cell_reference(start) and validate_cell_reference(end)):
                        raise ValidationError(f"Invalid cell range reference in formula: {ref}")
                else:  # Single cell reference
                    if not validate_cell_reference(ref):
                        raise ValidationError(f"Invalid cell reference in formula: {ref}")
    
            # Now check if there's a formula in the cell and compare
            sheet = wb[sheet_name]
            cell_obj = sheet[cell]
            current_formula = cell_obj.value
    
            # If cell has a formula (starts with =)
            if isinstance(current_formula, str) and current_formula.startswith('='):
                if formula.startswith('='):
                    if current_formula != formula:
                        return {
                            "message": "Formula is valid but doesn't match cell content",
                            "valid": True,
                            "matches": False,
                            "cell": cell,
                            "provided_formula": formula,
                            "current_formula": current_formula
                        }
                else:
                    if current_formula != f"={formula}":
                        return {
                            "message": "Formula is valid but doesn't match cell content",
                            "valid": True,
                            "matches": False,
                            "cell": cell,
                            "provided_formula": formula,
                            "current_formula": current_formula
                        }
                    else:
                        return {
                            "message": "Formula is valid and matches cell content",
                            "valid": True,
                            "matches": True,
                            "cell": cell,
                            "formula": formula
                        }
            else:
                return {
                    "message": "Formula is valid but cell contains no formula",
                    "valid": True,
                    "matches": False,
                    "cell": cell,
                    "provided_formula": formula,
                    "current_content": str(current_formula) if current_formula else ""
                }
    
        except ValidationError as e:
            logger.error(str(e))
            raise
        except Exception as e:
            logger.error(f"Failed to validate formula: {e}")
            raise ValidationError(str(e))
  • Supporting helper function for basic formula syntax validation, including parenthesis balancing and unsafe function detection.
    def validate_formula(formula: str) -> tuple[bool, str]:
        """Validate Excel formula syntax and safety"""
        if not formula.startswith("="):
            return False, "Formula must start with '='"
    
        # Remove the '=' prefix for validation
        formula = formula[1:]
    
        # Check for balanced parentheses
        parens = 0
        for c in formula:
            if c == "(":
                parens += 1
            elif c == ")":
                parens -= 1
            if parens < 0:
                return False, "Unmatched closing parenthesis"
    
        if parens > 0:
            return False, "Unclosed parenthesis"
    
        # Basic function name validation
        func_pattern = r"([A-Z]+)\("
        funcs = re.findall(func_pattern, formula)
        unsafe_funcs = {"INDIRECT", "HYPERLINK", "WEBSERVICE", "DGET", "RTD"}
    
        for func in funcs:
            if func in unsafe_funcs:
                return False, f"Unsafe function: {func}"
    
        return True, "Formula is valid"
Behavior2/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 states the tool validates syntax but does not explain what happens on success/failure (e.g., returns validation results or errors), whether it modifies the file, or any rate limits. This leaves key behavioral traits unspecified for a validation tool.

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 that is front-loaded with the core purpose. There is no wasted verbiage, making it highly concise and well-structured for quick understanding.

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 (4 parameters, no annotations) and the presence of an output schema (which likely covers return values), the description is minimally complete. However, it lacks details on parameter usage and behavioral context, leaving gaps in understanding how to effectively invoke the tool.

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%, so the description must compensate by explaining parameters. It adds no meaning beyond the schema, failing to clarify what 'cell', 'filepath', 'formula', and 'sheet_name' represent or their expected formats (e.g., formula syntax rules, file path validity). This is inadequate for 4 undocumented parameters.

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 ('validate Excel formula syntax') and distinguishes it from siblings like 'apply_formula' by explicitly noting 'without applying it.' It uses a precise verb ('validate') and resource ('Excel formula syntax'), making the purpose immediately apparent.

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

Usage Guidelines4/5

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

The description implies usage by specifying 'without applying it,' which differentiates it from 'apply_formula' as a pre-check alternative. However, it lacks explicit guidance on when to use this tool versus others like 'validate_excel_range' or prerequisites, such as file accessibility or formula format requirements.

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

Related 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/haris-musa/excel-mcp-server'

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