Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

create_workbook

Create a new Excel workbook in the xlwings Excel MCP Server. Use session_id for optimal performance when working within existing sessions.

Instructions

Create new Excel workbook.

Args:
    session_id: Session ID for creating workbook in existing session (optional)
    filepath: Path to create new Excel file (legacy, deprecated)
    
Note: Use session_id for better performance. filepath parameter is deprecated.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idNo
filepathNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary MCP tool handler and registration for 'create_workbook'. Handles both session-based (preferred) and legacy filepath modes by delegating to implementation helpers.
    def create_workbook(
        session_id: Optional[str] = None,
        filepath: Optional[str] = None
    ) -> str:
        """
        Create new Excel workbook.
        
        Args:
            session_id: Session ID for creating workbook in existing session (optional)
            filepath: Path to create new Excel file (legacy, deprecated)
            
        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 (though this is less common for creating new workbooks)
                session = SESSION_MANAGER.get_session(session_id)
                if not session:
                    return f"Error: Session {session_id} not found. Please open the workbook first using open_workbook()."
                
                with session.lock:
                    from xlwings_mcp.xlwings_impl.workbook_xlw import create_workbook_xlw_with_wb
                    result = create_workbook_xlw_with_wb(session.workbook)
                    return result.get("message", "Workbook created successfully") if "error" not in result else f"Error: {result['error']}"
            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.workbook import create_workbook as create_workbook_impl
                create_workbook_impl(full_path)
                return f"Created workbook at {full_path}"
            else:
                return ERROR_TEMPLATES['PARAMETER_MISSING'].format(
                    param1='session_id',
                    param2='filepath'
                )
            
        except WorkbookError as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error creating workbook: {e}")
            raise
  • Legacy wrapper function called by the main handler for filepath mode. Delegates to xlwings-specific implementation.
    def create_workbook(filepath: str, sheet_name: str = "Sheet1") -> dict[str, Any]:
        """Create a new Excel workbook with optional custom sheet name"""
        result = create_workbook_xlw(filepath, sheet_name)
        if "error" in result:
            raise WorkbookError(result["error"])
        return result
  • Core xlwings implementation for creating a new workbook using excel_context context manager. Called by legacy wrapper.
    def create_workbook_xlw(
        filepath: str,
        sheet_name: Optional[str] = None
    ) -> Dict[str, Any]:
        """xlwings를 사용한 새 워크북 생성
        
        Args:
            filepath: 생성할 파일 경로
            sheet_name: 기본 시트명 (optional, defaults to Excel's default)
            
        Returns:
            생성 결과 딕셔너리
        """
        try:
            # Use Excel's default sheet name if not provided
            if not sheet_name:
                sheet_name = "Sheet1"  # Excel's default
            
            # Excel context로 새 워크북 생성
            with excel_context(filepath, create_if_not_exists=True, sheet_name=sheet_name) as wb:
                # 워크북이 이미 저장되었으므로 추가 작업 없음
                return {
                    "message": f"Created workbook: {filepath}",
                    "filepath": filepath,
                    "active_sheet": sheet_name
                }
            
        except Exception as e:
            logger.error(f"xlwings 워크북 생성 실패: {e}")
            return {"error": f"Failed to create workbook: {str(e)}"}
  • Session-based xlwings helper for configuring an existing workbook object (used by main handler in session mode).
    def create_workbook_xlw_with_wb(wb, sheet_name: Optional[str] = None) -> Dict[str, Any]:
        """Session-based version using existing workbook object.
        
        Args:
            wb: Workbook object from session
            sheet_name: 기본 시트명 (optional, defaults to Excel's default)
            
        Returns:
            생성 결과 딕셔너리
        """
        try:
            # This is a special case - when wb is provided, we might add sheets or modify it
            # For a new workbook, typically the workbook creation was handled in session setup
            # But we can still configure it here
            
            if sheet_name and wb.sheets:
                # Rename the first sheet if sheet_name is provided
                first_sheet = wb.sheets[0]
                if first_sheet.name != sheet_name:
                    first_sheet.name = sheet_name
            
            # Save the workbook to ensure changes persist
            wb.save()
            
            return {
                "message": f"Workbook configured successfully",
                "active_sheet": wb.sheets[0].name if wb.sheets else None,
                "sheet_count": len(wb.sheets)
            }
            
        except Exception as e:
            logger.error(f"xlwings 워크북 설정 실패: {e}")
            return {"error": f"Failed to configure workbook: {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"
      +}
    • removedInput schema / required
      Removed value: -[
      -  "filepath"
      -]
  2. First observed

TDQS

B3.4/5.0
Behavior2/5

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

No annotations exist, so the description must carry the full burden. It does not disclose whether the tool overwrites existing files, requires specific permissions, or has side effects like saving to disk. The note about session_id hints at session association but lacks clarity.

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 with two sentences for purpose and two lines for parameters. It is front-loaded with the core purpose, but could be more structured (e.g., separate usage and notes sections). Still, no redundancy.

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, the description is partially complete. It lacks details on error conditions, prerequisites (e.g., need for an open session), and what the output contains. For a creation tool, this is a moderate gap.

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?

With 0% schema description coverage, the description adds meaningful context: session_id is for existing sessions, filepath is deprecated. This goes beyond mere type information, though more detail (e.g., format of session_id) would be helpful.

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 'Create new Excel workbook' clearly states the verb and resource, distinguishing it from siblings like open_workbook (opens existing) and create_worksheet (creates sheet within 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?

The description provides almost no guidance on when to use this tool versus alternatives. It mentions a deprecation note for filepath and recommends session_id, but does not discuss selection criteria among sibling tools.

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