From d24ce4b97c930f1bdd61e2d0b27605a08aec5c91 Mon Sep 17 00:00:00 2001 From: Matteo Scanzano Date: Sat, 5 Jul 2025 10:29:18 +0200 Subject: [PATCH] Add tool to get merged cells (#59) --- TOOLS.md | 13 +++++++++++++ src/excel_mcp/server.py | 13 +++++++++++++ src/excel_mcp/sheet.py | 15 +++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/TOOLS.md b/TOOLS.md index f3c8be4..07a8ec6 100644 --- a/TOOLS.md +++ b/TOOLS.md @@ -145,6 +145,19 @@ unmerge_cells(filepath: str, sheet_name: str, start_cell: str, end_cell: str) -> - `end_cell`: Ending cell of range - Returns: Success message +### get_merged_cells + +Get merged cells in a worksheet. + +```python +get_merged_cells(filepath: str, sheet_name: str) -> str +``` + +- `filepath`: Path to Excel file +- `sheet_name`: Target worksheet name +- Returns: String representation of merged cells + + ## Formula Operations ### apply_formula diff --git a/src/excel_mcp/server.py b/src/excel_mcp/server.py index 0fc47cf..8fcdf64 100644 --- a/src/excel_mcp/server.py +++ b/src/excel_mcp/server.py @@ -32,6 +32,7 @@ from excel_mcp.sheet import ( rename_sheet, merge_range, unmerge_range, + get_merged_ranges, ) # Get project root directory path for log file path. @@ -469,6 +470,18 @@ def unmerge_cells(filepath: str, sheet_name: str, start_cell: str, end_cell: str logger.error(f"Error unmerging cells: {e}") raise +@mcp.tool() +def get_merged_cells(filepath: str, sheet_name: str) -> str: + """Get merged cells in a worksheet.""" + try: + full_path = get_excel_path(filepath) + return str(get_merged_ranges(full_path, sheet_name)) + except (ValidationError, SheetError) as e: + return f"Error: {str(e)}" + except Exception as e: + logger.error(f"Error getting merged cells: {e}") + raise + @mcp.tool() def copy_range( filepath: str, diff --git a/src/excel_mcp/sheet.py b/src/excel_mcp/sheet.py index 0fc7da3..034f6e6 100644 --- a/src/excel_mcp/sheet.py +++ b/src/excel_mcp/sheet.py @@ -243,6 +243,21 @@ def unmerge_range(filepath: str, sheet_name: str, start_cell: str, end_cell: str logger.error(f"Failed to unmerge range: {e}") raise SheetError(str(e)) +def get_merged_ranges(filepath: str, sheet_name: str) -> list[str]: + """Get merged cells in a worksheet.""" + try: + wb = load_workbook(filepath) + if sheet_name not in wb.sheetnames: + raise SheetError(f"Sheet '{sheet_name}' not found") + worksheet = wb[sheet_name] + return [str(merged_range) for merged_range in worksheet.merged_cells.ranges] + except SheetError as e: + logger.error(str(e)) + raise + except Exception as e: + logger.error(f"Failed to get merged cells: {e}") + raise SheetError(str(e)) + def copy_range_operation( filepath: str, sheet_name: str,