Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

rename_worksheet

Change worksheet names in Excel workbooks through the xlwings Excel MCP Server. Provide session ID, current name, and new name to update sheet labels for better organization.

Instructions

Rename worksheet in workbook.

Args:
    session_id: Session ID from open_workbook (required)
    old_name: Current name of the worksheet
    new_name: New name for the worksheet

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
old_nameYes
new_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Registration and handler for the 'rename_worksheet' MCP tool. Validates session and delegates to xlwings implementation.
    @mcp.tool()
    def rename_worksheet(
        session_id: str,
        old_name: str,
        new_name: str
    ) -> str:
        """
        Rename worksheet in workbook.
        
        Args:
            session_id: Session ID from open_workbook (required)
            old_name: Current name of the worksheet
            new_name: New name for the worksheet
        """
        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.sheet_xlw import rename_worksheet_xlw_with_wb
                result = rename_worksheet_xlw_with_wb(session.workbook, old_name, new_name)
            
            return result.get("message", "Worksheet renamed 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 renaming worksheet: {e}")
            raise
  • Core xlwings implementation for renaming a worksheet using an existing workbook object (session-based). Performs validation, renames sheet, and saves.
    def rename_worksheet_xlw_with_wb(wb, old_name: str, new_name: str) -> Dict[str, Any]:
        """Session-based version using existing workbook object.
        
        Args:
            wb: Workbook object from session
            old_name: 기존 시트명
            new_name: 새 시트명
            
        Returns:
            이름 변경 결과 딕셔너리
        """
        try:
            # 기존 시트 확인
            existing_sheets = [sheet.name for sheet in wb.sheets]
            if old_name not in existing_sheets:
                return {"error": f"Sheet '{old_name}' not found"}
            
            # 새 이름 중복 확인
            if new_name in existing_sheets:
                return {"error": f"Sheet '{new_name}' already exists"}
            
            # 시트 이름 변경
            wb.sheets[old_name].name = new_name
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet renamed from '{old_name}' to '{new_name}'"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 이름 변경 실패: {e}")
            return {"error": f"Failed to rename worksheet: {str(e)}"}
  • Wrapper function in sheet.py that calls the non-session xlwings rename_worksheet_xlw implementation (legacy/non-primary path).
    def rename_sheet(filepath: str, old_name: str, new_name: str) -> Dict[str, Any]:
        """Rename a worksheet."""
        result = rename_worksheet_xlw(filepath, old_name, new_name)
        if "error" in result:
            raise SheetError(result["error"])
        return result
  • Non-session (filepath-based) xlwings implementation for renaming worksheet. Opens workbook, renames, saves, and cleans up Excel app.
    def rename_worksheet_xlw(filepath: str, old_name: str, new_name: str) -> Dict[str, Any]:
        """xlwings를 사용한 워크시트 이름 변경
    
        Args:
            filepath: Excel 파일 경로
            old_name: 기존 시트명
            new_name: 새 시트명
    
        Returns:
            이름 변경 결과 딕셔너리
        """
        app = None
        wb = None
    
        # Initialize COM for thread safety (Windows)
        _com_initialize()
    
        try:
            # 파일 경로 검증
            file_path = Path(filepath)
            if not file_path.exists():
                return {"error": f"File not found: {filepath}"}
            
            # Excel 앱 시작
            app = xw.App(visible=False, add_book=False)
            
            # 워크북 열기
            wb = app.books.open(filepath)
            
            # 기존 시트 확인
            existing_sheets = [sheet.name for sheet in wb.sheets]
            if old_name not in existing_sheets:
                return {"error": f"Sheet '{old_name}' not found"}
            
            # 새 이름 중복 확인
            if new_name in existing_sheets:
                return {"error": f"Sheet '{new_name}' already exists"}
            
            # 시트 이름 변경
            wb.sheets[old_name].name = new_name
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet renamed from '{old_name}' to '{new_name}'"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 이름 변경 실패: {e}")
            return {"error": f"Failed to rename worksheet: {str(e)}"}
            
        finally:
            # 리소스 정리
            if wb:
                try:
                    wb.close()
                except Exception as e:
                    logger.warning(f"워크북 닫기 실패: {e}")
            
            if app:
                try:
                    app.quit()
                except Exception as e:
                    logger.warning(f"Excel 앱 종료 실패: {e}")
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states 'Rename worksheet in workbook' which implies a mutation, but fails to describe critical behaviors: whether renaming requires specific permissions, what happens if the new name conflicts with existing worksheets, if the change is reversible, or any rate limits. This leaves significant gaps for a mutation tool.

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 appropriately sized and front-loaded: the first sentence states the core purpose, followed by a structured 'Args:' section that efficiently lists parameters with brief explanations. Every sentence earns its place with no redundant information.

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 moderate complexity (3 parameters, mutation operation) and the presence of an output schema (which reduces need to explain return values), the description is partially complete. It covers basic purpose and parameter meanings but lacks behavioral details and usage guidelines, making it adequate but with clear gaps for safe operation.

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?

The description adds meaningful context beyond the input schema, which has 0% description coverage. It explains that 'session_id' is 'from open_workbook (required)', clarifies 'old_name' as 'Current name of the worksheet', and 'new_name' as 'New name for the worksheet', providing essential semantics that the schema lacks. However, it doesn't detail constraints like name length or allowed characters.

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 verb 'Rename' and the resource 'worksheet in workbook', making the purpose immediately understandable. It distinguishes itself from siblings like 'create_worksheet' or 'delete_worksheet' by focusing on name modification, though it doesn't explicitly differentiate from similar tools like 'copy_worksheet' which might also involve naming.

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 mentions 'session_id: Session ID from open_workbook (required)', implying a prerequisite, but offers no explicit when/when-not rules or comparisons to sibling tools like 'copy_worksheet' or 'create_worksheet' that might affect naming decisions.

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