Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

apply_formula

Insert Excel formulas into specific worksheet cells using xlwings MCP server for automated spreadsheet calculations and data processing.

Instructions

Apply Excel formula to cell.

Args:
    session_id: Session ID from open_workbook (required)
    sheet_name: Name of worksheet
    cell: Cell address (e.g., "A1")
    formula: Excel formula to apply

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
sheet_nameYes
cellYes
formulaYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core implementation of the apply_formula tool logic for session-based workbook using xlwings. Applies formula to specified cell, normalizes it, calculates result, saves workbook, and returns detailed response.
    def apply_formula_xlw_with_wb(
        wb,
        sheet_name: str,
        cell: str,
        formula: str
    ) -> Dict[str, Any]:
        """Apply formula using existing workbook object (session-based).
        
        Args:
            wb: Workbook object from session
            sheet_name: Sheet name
            cell: Target cell (e.g., A1)
            formula: Formula to apply
            
        Returns:
            Dictionary with result and calculated value
        """
        try:
            # Check sheet exists
            if sheet_name not in [s.name for s in wb.sheets]:
                return {"error": f"Sheet '{sheet_name}' not found"}
            
            ws = wb.sheets[sheet_name]
            
            # Normalize formula
            if not formula.startswith('='):
                formula = f'={formula}'
            
            # Get cell
            cell_range = ws.range(cell)
            
            # Apply formula
            try:
                cell_range.formula = formula
            except Exception as e:
                return {
                    "error": f"Formula error in cell {cell}: {str(e)}",
                    "formula": formula,
                    "cell": cell
                }
            
            # Get calculated result
            try:
                calculated_value = cell_range.value
                display_value = cell_range.api.Text
            except Exception as e:
                logger.warning(f"Failed to read calculated value: {e}")
                calculated_value = None
                display_value = None
            
            # Save workbook
            wb.save()
            
            return {
                "message": f"Formula applied to {cell}",
                "cell": cell,
                "formula": formula,
                "calculated_value": calculated_value,
                "display_value": display_value
            }
            
        except Exception as e:
            logger.error(f"Failed to apply formula: {e}")
            return {"error": f"Failed to apply formula: {str(e)}"}
  • MCP tool registration using @mcp.tool() decorator. Defines input schema via parameters and docstring, validates session, calls the handler, and handles errors.
    @mcp.tool()
    def apply_formula(
        session_id: str,
        sheet_name: str,
        cell: str,
        formula: str
    ) -> str:
        """
        Apply Excel formula to cell.
        
        Args:
            session_id: Session ID from open_workbook (required)
            sheet_name: Name of worksheet
            cell: Cell address (e.g., "A1")
            formula: Excel formula to apply
        """
        try:
            # Validate session using centralized helper
            session = get_validated_session(session_id)
            if isinstance(session, str):  # Error message returned
                return session
            
            with session.lock:
                from xlwings_mcp.xlwings_impl.calculations_xlw import apply_formula_xlw_with_wb
                result = apply_formula_xlw_with_wb(session.workbook, sheet_name, cell, formula)
            
            return result.get("message", "Formula applied successfully") if "error" not in result else f"Error: {result['error']}"
                
        except (ValidationError, CalculationError) as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error applying formula: {e}")
            raise

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed3 schema fields changed
    • removedInput schema / properties / filepath
      Removed value: -{
      -  "title": "Filepath",
      -  "type": "string"
      -}
    • addedInput schema / properties / session_id
      Added value: +{
      +  "title": "Session Id",
      +  "type": "string"
      +}
    • changedInput schema / required
      Previous value: -[
      -  "filepath",
      -  "sheet_name",
      -  "cell",
      -  "formula"
      -]New value: +[
      +  "session_id",
      +  "sheet_name",
      +  "cell",
      +  "formula"
      +]
  2. First observed

TDQS

B3.3/5.0
Behavior2/5

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

The description only states the action without disclosing behavioral details. Without annotations, the agent is not informed about potential side effects (e.g., overwriting cell content), error behavior, or whether the formula is immediately evaluated. The output schema exists but the description does not mention what is returned.

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 extremely concise: a one-line verb phrase followed by a clear parameter list. Every sentence earns its place, and the structure is front-loaded with the purpose. No unnecessary words.

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 4 required parameters and an output schema, the description covers the basic function but lacks completeness. It does not explain the relationship between this tool and siblings (e.g., when to use apply_formula vs write_data_to_excel), nor does it mention error handling or the need for a valid session. The output schema is present but not leveraged in the description.

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 description includes parameter explanations (e.g., 'session_id: Session ID from open_workbook') that add meaning beyond the input schema's type and title. However, the formula parameter is described vaguely as 'Excel formula to apply', missing details like supported syntax or escape rules. With 0% schema description coverage, the description partially compensates but could be more specific.

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 'Apply Excel formula to cell' is a specific verb+resource that clearly states what the tool does. It distinguishes itself from sibling tools like 'validate_formula_syntax' and 'write_data_to_excel' by focusing on formula application. No ambiguity.

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 does not mention prerequisites (e.g., an active session from open_workbook) or context where other tools like 'write_data_to_excel' might be more appropriate. This lack of usage direction leaves the agent uninformed.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.