Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

copy_range

Copy Excel cell ranges between locations or worksheets to reorganize data, duplicate content, or prepare reports. Specify source and target ranges with optional sheet names for flexible data management.

Instructions

Copy a range of cells to another location.

Args:
    sheet_name: Name of source worksheet
    source_start: Starting cell of source range
    source_end: Ending cell of source range
    target_start: Starting cell of target range
    session_id: Session ID from open_workbook (preferred)
    filepath: Path to Excel file (legacy, deprecated)
    target_sheet: Target worksheet (optional, uses source sheet if not provided)
    
Note: Use session_id for better performance. filepath parameter is deprecated.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sheet_nameYes
source_startYes
source_endYes
target_startYes
session_idNo
filepathNo
target_sheetNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Handler and registration for the 'copy_range' MCP tool. Dispatches to session-based or legacy filepath implementations in range_xlw.py.
    @mcp.tool()
    def copy_range(
        sheet_name: str,
        source_start: str,
        source_end: str,
        target_start: str,
        session_id: Optional[str] = None,
        filepath: Optional[str] = None,
        target_sheet: Optional[str] = None
    ) -> str:
        """
        Copy a range of cells to another location.
        
        Args:
            sheet_name: Name of source worksheet
            source_start: Starting cell of source range
            source_end: Ending cell of source range
            target_start: Starting cell of target range
            session_id: Session ID from open_workbook (preferred)
            filepath: Path to Excel file (legacy, deprecated)
            target_sheet: Target worksheet (optional, uses source sheet if not provided)
            
        Note: Use session_id for better performance. filepath parameter is deprecated.
        """
        try:
            # Support both new (session_id) and old (filepath) API
            if session_id:
                # New API: use session
                session = SESSION_MANAGER.get_session(session_id)
                if not session:
                    return ERROR_TEMPLATES['SESSION_NOT_FOUND'].format(
                        session_id=session_id, 
                        ttl=10  # Default TTL is 10 minutes (600 seconds)
                    )
                
                with session.lock:
                    from xlwings_mcp.xlwings_impl.range_xlw import copy_range_xlw_with_wb
                    result = copy_range_xlw_with_wb(
                        session.workbook,
                        sheet_name,
                        source_start,
                        source_end,
                        target_start,
                        target_sheet or sheet_name  # Use source sheet if target_sheet is None
                    )
            elif filepath:
                # Legacy API: backwards compatibility
                logger.warning("Using deprecated filepath parameter. Please use session_id instead.")
                full_path = get_excel_path(filepath)
                from xlwings_mcp.xlwings_impl.range_xlw import copy_range_xlw
                result = copy_range_xlw(
                    full_path,
                    sheet_name,
                    source_start,
                    source_end,
                    target_start,
                    target_sheet or sheet_name  # Use source sheet if target_sheet is None
                )
            else:
                return ERROR_TEMPLATES['PARAMETER_MISSING'].format(
                    param1='session_id',
                    param2='filepath'
                )
            
            return result.get("message", "Range copied successfully") if "error" not in result else f"Error: {result['error']}"
        except (ValidationError, SheetError) as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error copying range: {e}")
            raise
  • Legacy (filepath-based) core implementation of range copying using xlwings. Opens workbook, copies range preserving formats/formulas, saves, and closes.
    def copy_range_xlw(
        filepath: str, 
        sheet_name: str, 
        source_start: str, 
        source_end: str, 
        target_start: str,
        target_sheet: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Copy a range of cells to another location using xlwings.
        
        Args:
            filepath: Path to Excel file
            sheet_name: Name of source worksheet
            source_start: Top-left cell of source range
            source_end: Bottom-right cell of source range
            target_start: Top-left cell of target location
            target_sheet: Name of target worksheet (optional, defaults to source sheet)
            
        Returns:
            Dict with success message or error
        """
        app = None
        wb = None
    
        # Initialize COM for thread safety (Windows)
        _com_initialize()
    
        try:
            # Use target_sheet if provided, otherwise use source sheet
            target_sheet = target_sheet or sheet_name
    
            logger.info(f"Copying range {source_start}:{source_end} to {target_start} in {target_sheet}")
            
            # Check if file exists
            if not os.path.exists(filepath):
                return {"error": f"File not found: {filepath}"}
            
            # Open Excel app and workbook
            app = xw.App(visible=False, add_book=False)
            wb = app.books.open(filepath)
            
            # Check if sheets exist
            sheet_names = [s.name for s in wb.sheets]
            if sheet_name not in sheet_names:
                return {"error": f"Source sheet '{sheet_name}' not found"}
            if target_sheet not in sheet_names:
                return {"error": f"Target sheet '{target_sheet}' not found"}
            
            source_sheet = wb.sheets[sheet_name]
            dest_sheet = wb.sheets[target_sheet]
            
            # Get source range
            source_range = source_sheet.range(f"{source_start}:{source_end}")
            
            # Copy to target location
            # xlwings copy method preserves formatting and formulas
            source_range.copy(destination=dest_sheet.range(target_start))
            
            # Calculate target end cell
            rows = source_range.rows.count
            cols = source_range.columns.count
            target_end_row = dest_sheet.range(target_start).row + rows - 1
            target_end_col = dest_sheet.range(target_start).column + cols - 1
            target_end = dest_sheet.cells(target_end_row, target_end_col).address.replace("$", "")
            
            # Save the workbook
            wb.save()
            
            logger.info(f"✅ Successfully copied range to {target_start}:{target_end}")
            return {
                "message": f"Successfully copied range {source_start}:{source_end} to {target_start}",
                "source_range": f"{source_start}:{source_end}",
                "target_range": f"{target_start}:{target_end}",
                "source_sheet": sheet_name,
                "target_sheet": target_sheet
            }
            
        except Exception as e:
            logger.error(f"❌ Error copying range: {str(e)}")
            return {"error": str(e)}
            
        finally:
            if wb:
                wb.close()
            if app:
                app.quit()
  • Session-based (with existing workbook) core implementation of range copying using xlwings. Copies range preserving formats/formulas and saves.
    def copy_range_xlw_with_wb(
        wb,
        sheet_name: str, 
        source_start: str, 
        source_end: str, 
        target_start: str,
        target_sheet: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Session-based range copying using existing workbook object.
        
        Args:
            wb: Workbook object from session
            sheet_name: Name of source worksheet
            source_start: Top-left cell of source range
            source_end: Bottom-right cell of source range
            target_start: Top-left cell of target location
            target_sheet: Name of target worksheet (optional, defaults to source sheet)
            
        Returns:
            Dict with success message or error
        """
        try:
            # Use target_sheet if provided, otherwise use source sheet
            target_sheet = target_sheet or sheet_name
            
            logger.info(f"📋 Copying range {source_start}:{source_end} to {target_start} in {target_sheet}")
            
            # Check if sheets exist
            sheet_names = [s.name for s in wb.sheets]
            if sheet_name not in sheet_names:
                return {"error": f"Source sheet '{sheet_name}' not found"}
            if target_sheet not in sheet_names:
                return {"error": f"Target sheet '{target_sheet}' not found"}
            
            source_sheet = wb.sheets[sheet_name]
            dest_sheet = wb.sheets[target_sheet]
            
            # Get source range
            source_range = source_sheet.range(f"{source_start}:{source_end}")
            
            # Copy to target location
            # xlwings copy method preserves formatting and formulas
            source_range.copy(destination=dest_sheet.range(target_start))
            
            # Calculate target end cell
            rows = source_range.rows.count
            cols = source_range.columns.count
            target_end_row = dest_sheet.range(target_start).row + rows - 1
            target_end_col = dest_sheet.range(target_start).column + cols - 1
            target_end = dest_sheet.cells(target_end_row, target_end_col).address.replace("$", "")
            
            # Save the workbook
            wb.save()
            
            logger.info(f"✅ Successfully copied range to {target_start}:{target_end}")
            return {
                "message": f"Successfully copied range {source_start}:{source_end} to {target_start}",
                "source_range": f"{source_start}:{source_end}",
                "target_range": f"{target_start}:{target_end}",
                "source_sheet": sheet_name,
                "target_sheet": target_sheet
            }
            
        except Exception as e:
            logger.error(f"❌ Error copying range: {str(e)}")
            return {"error": str(e)}

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed5 schema fields changed
    • addedInput schema / properties / filepath / anyOf
      Added value: +[
      +  {
      +    "type": "string"
      +  },
      +  {
      +    "type": "null"
      +  }
      +]
    • addedInput schema / properties / filepath / default
      Added value: +null
    • removedInput schema / properties / filepath / type
      Removed value: -"string"
    • addedInput schema / properties / session_id
      Added value: +{
      +  "anyOf": [
      +    {
      +      "type": "string"
      +    },
      +    {
      +      "type": "null"
      +    }
      +  ],
      +  "default": null,
      +  "title": "Session Id"
      +}
    • changedInput schema / required
      Previous value: -[
      -  "filepath",
      -  "sheet_name",
      -  "source_start",
      -  "source_end",
      -  "target_start"
      -]New value: +[
      +  "sheet_name",
      +  "source_start",
      +  "source_end",
      +  "target_start"
      +]
  2. First observed

TDQS

A3.8/5.0
Behavior2/5

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

With no annotations, the description carries the full burden of behavioral disclosure. It fails to mention what happens on overwrite, formatting preservation, or side effects, focusing only on parameters.

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 concise and well-structured with a purpose line, Args list, and note, though the note could be integrated for brevity.

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 complexity and the presence of an output schema, the description covers parameters adequately but misses prerequisites (e.g., workbook must be open) and edge cases.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description provides brief explanations for each parameter (e.g., 'Name of source worksheet'), adding meaning beyond the schema titles.

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 action ('Copy a range of cells to another location') with a specific verb and resource, distinguishing it from sibling tools like delete_range or format_range.

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 includes a note on preferring session_id over deprecated filepath, providing context for parameter choice, but does not explicitly state when to use this tool versus alternatives or exclude scenarios.

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