Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

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
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Apply Excel formula to cell' implies a write/mutation operation, it doesn't disclose important behavioral aspects: whether this overwrites existing content, what happens with formula errors, whether it triggers workbook recalculation, or what permissions are required. The description provides minimal behavioral context beyond the basic action statement.

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 concise with a clear main statement followed by a parameter list. The structure is logical and front-loaded with the core functionality. However, the parameter explanations are minimal (just repeating parameter names with basic examples), and there's some wasted space in the formatting with excessive line breaks.

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 that this is a mutation tool with 4 parameters, 0% schema coverage, no annotations, but with an output schema present, the description is minimally adequate. The presence of an output schema means the description doesn't need to explain return values, but it should provide more context about the mutation behavior, error conditions, and relationship to sibling tools. The description covers the basics but leaves significant gaps for a tool that modifies spreadsheet content.

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?

With 0% schema description coverage, the description partially compensates by listing all 4 parameters with brief explanations. However, it provides minimal semantic context beyond parameter names - for example, it doesn't explain what constitutes a valid 'cell' format beyond the 'A1' example, what types of formulas are supported, or how sheet_name interacts with the session. The parameter documentation is present but superficial.

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 action ('Apply Excel formula') and target ('to cell'), providing a specific verb+resource combination. However, it doesn't differentiate this tool from sibling tools like 'write_data_to_excel' or 'format_range' that might also modify cell content, leaving room for confusion about when to choose this specific formula application method.

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. There's no mention of prerequisites (like requiring an open workbook session), comparison to similar tools (like 'write_data_to_excel' for static values), or any context about appropriate use cases for formula application versus direct data writing.

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/hyunjae-labs/xlwings-mcp-server'

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