Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

delete_worksheet

Remove a specific worksheet from an Excel workbook using the xlwings Excel MCP Server. Specify the workbook session and sheet name to delete unwanted worksheets.

Instructions

Delete worksheet from workbook.

Args:
    session_id: Session ID from open_workbook (required)
    sheet_name: Name of the worksheet to delete

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
sheet_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main tool handler decorated with @mcp.tool(). Validates session, acquires lock, imports and calls the xlwings implementation delete_worksheet_xlw_with_wb, handles errors and returns result message.
    def delete_worksheet(
        session_id: str,
        sheet_name: str
    ) -> str:
        """
        Delete worksheet from workbook.
        
        Args:
            session_id: Session ID from open_workbook (required)
            sheet_name: Name of the worksheet to delete
        """
        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 delete_worksheet_xlw_with_wb
                result = delete_worksheet_xlw_with_wb(session.workbook, sheet_name)
            
            return result.get("message", "Worksheet deleted 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 deleting worksheet: {e}")
            raise
  • Core xlwings implementation for deleting a worksheet using an existing workbook object (session-based). Checks if sheet exists and is not the only one, deletes it via wb.sheets[sheet_name].delete(), saves the workbook, returns success/error dict.
    def delete_worksheet_xlw_with_wb(wb, sheet_name: str) -> Dict[str, Any]:
        """Session-based version using existing workbook object.
        
        Args:
            wb: Workbook object from session
            sheet_name: 삭제할 시트명
            
        Returns:
            삭제 결과 딕셔너리
        """
        try:
            # 시트 존재 확인
            existing_sheets = [sheet.name for sheet in wb.sheets]
            if sheet_name not in existing_sheets:
                return {"error": f"Sheet '{sheet_name}' not found"}
            
            # 시트가 1개만 있으면 삭제 불가
            if len(wb.sheets) == 1:
                return {"error": "Cannot delete the only sheet in workbook"}
            
            # 시트 삭제
            wb.sheets[sheet_name].delete()
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet '{sheet_name}' deleted successfully"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 삭제 실패: {e}")
            return {"error": f"Failed to delete worksheet: {str(e)}"}
  • Filepath-based xlwings implementation for deleting worksheet. Opens workbook, performs same checks and deletion as session version, cleans up app and workbook resources.
    def delete_worksheet_xlw(filepath: str, sheet_name: str) -> Dict[str, Any]:
        """xlwings를 사용한 워크시트 삭제
    
        Args:
            filepath: Excel 파일 경로
            sheet_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 sheet_name not in existing_sheets:
                return {"error": f"Sheet '{sheet_name}' not found"}
            
            # 시트가 1개만 있으면 삭제 불가
            if len(wb.sheets) == 1:
                return {"error": "Cannot delete the only sheet in workbook"}
            
            # 시트 삭제
            wb.sheets[sheet_name].delete()
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet '{sheet_name}' deleted successfully"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 삭제 실패: {e}")
            return {"error": f"Failed to delete 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}")
  • The @mcp.tool() decorator registers this function as the MCP tool named "delete_worksheet" with input schema derived from function parameters.
    def delete_worksheet(
        session_id: str,
        sheet_name: str
    ) -> str:
        """
        Delete worksheet from workbook.
        
        Args:
            session_id: Session ID from open_workbook (required)
            sheet_name: Name of the worksheet to delete
        """
        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 delete_worksheet_xlw_with_wb
                result = delete_worksheet_xlw_with_wb(session.workbook, sheet_name)
            
            return result.get("message", "Worksheet deleted 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 deleting worksheet: {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. It states the destructive action 'Delete' but doesn't elaborate on critical behaviors: whether deletion is permanent/reversible, what happens to dependent formulas/charts, if it requires specific permissions, or error conditions (e.g., deleting the last worksheet). The mention of 'session_id' hints at stateful operation but doesn't explain session management implications.

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 brief with three sentences: a clear purpose statement followed by parameter explanations. Each sentence adds value without redundancy. The structure is front-loaded with the core action, though the parameter section could be slightly more integrated. There's no wasted text, making it efficient for an agent to parse.

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 a destructive operation with no annotations but an output schema (which handles return values), the description is minimally adequate. It covers the basic action and parameters but lacks important context: no warnings about data loss, no mention of workbook state changes, and no guidance on error handling. For a deletion tool, this leaves significant gaps in understanding behavioral implications.

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 for both parameters beyond the 0% schema coverage. It explains 'session_id' comes 'from open_workbook' and is 'required', and 'sheet_name' identifies 'the worksheet to delete'. This clarifies parameter purposes and relationships that aren't in the schema titles alone. With 2 parameters and good semantic clarification, it compensates well for the lack of schema descriptions.

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 'Delete' and the resource 'worksheet from workbook', making the purpose unambiguous. It distinguishes itself from sibling tools like 'delete_range', 'delete_sheet_columns', and 'delete_sheet_rows' by specifying it deletes entire worksheets rather than ranges or rows/columns. However, it doesn't explicitly differentiate from 'close_workbook' or 'force_close_workbook_by_path_tool', which might also involve workbook modifications.

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 doesn't mention prerequisites (e.g., needing an open workbook session), consequences (e.g., data loss), or when to choose other deletion tools like 'delete_range'. The only implied context is the 'session_id' parameter reference to 'open_workbook', but this isn't explicit usage guidance.

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