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

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"

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