Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

create_worksheet

Add a new worksheet to an Excel workbook using the xlwings Excel MCP Server. Specify a session ID and sheet name to organize data within workbooks.

Instructions

Create new worksheet in workbook.

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
sheet_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool registration and handler for 'create_worksheet'. Validates session, locks it, and calls the xlwings implementation.
    @mcp.tool()
    def create_worksheet(
        session_id: str,
        sheet_name: str
    ) -> str:
        """
        Create new worksheet in workbook.
        
        Args:
            session_id: Session ID from open_workbook (required)
            sheet_name: Name of the new 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 create_worksheet_xlw_with_wb
                result = create_worksheet_xlw_with_wb(session.workbook, sheet_name)
            
            return result.get("message", "Worksheet created successfully") if "error" not in result else f"Error: {result['error']}"
            
        except (ValidationError, WorkbookError) as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error creating worksheet: {e}")
            raise
  • Core handler logic: checks if sheet exists, adds new sheet using wb.sheets.add(), saves workbook.
    def create_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 in existing_sheets:
                return {"error": f"Sheet '{sheet_name}' already exists"}
            
            # 새 시트 추가
            wb.sheets.add(name=sheet_name)
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet '{sheet_name}' created successfully"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 생성 실패: {e}")
            return {"error": f"Failed to create worksheet: {str(e)}"}
  • Non-session helper: opens workbook from filepath, creates sheet, handles COM, cleanup.
    def create_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 in existing_sheets:
                return {"error": f"Sheet '{sheet_name}' already exists"}
            
            # 새 시트 추가
            wb.sheets.add(name=sheet_name)
            
            # 파일 저장
            wb.save()
            
            return {"message": f"Sheet '{sheet_name}' created successfully"}
            
        except Exception as e:
            logger.error(f"xlwings 워크시트 생성 실패: {e}")
            return {"error": f"Failed to create 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}")

Schema Changelog

Changes observed during successful MCP inspections.

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

TDQS

C2.9/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 only states it creates a worksheet, but omits any side effects, constraints (e.g., duplicate sheet names), or return value details. The existence of an output schema is not utilized in the description.

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 very short and front-loaded with the purpose. The args are listed concisely. While there is some redundancy (the 'Args' section repeats parameter names), it is still efficient and easily parsed.

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 simplicity and the presence of an output schema (not shown but known), the description is adequate but not fully complete. It does not cover error cases (e.g., invalid session, duplicate sheet name) or confirm what is returned, leaving some gaps for an agent.

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?

The schema has 0% description coverage, but the description adds brief explanations for both parameters: session_id is 'Session ID from open_workbook' and sheet_name is 'Name of the new worksheet'. This adds some value beyond the schema's type and title, though it remains minimal.

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 tool creates a new worksheet in a workbook, which is distinct from sibling tools like rename_worksheet or delete_worksheet. However, it does not explicitly differentiate from create_workbook, but contextually the session_id parameter implies an existing workbook.

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?

No guidance on when to use this tool versus alternatives is provided. The description mentions session_id from open_workbook implicitly, but does not state prerequisites or scenarios where this tool should be used or avoided.

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