Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

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)}"}
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions performance implications ('better performance') and deprecation status, which adds useful context beyond basic functionality. However, it doesn't describe what happens after creation (e.g., whether the workbook is opened in memory, saved to disk, or requires subsequent actions), which would be important for a creation 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 perfectly structured and concise: a clear purpose statement followed by parameter explanations in a labeled 'Args' section and a 'Note' for additional guidance. Every sentence earns its place with no wasted words, and the information is front-loaded with the main purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given that there's an output schema (which handles return values), no annotations, and only 2 parameters with good description coverage, the description is reasonably complete. It covers the core purpose and parameter semantics adequately. However, for a creation tool, it could benefit from mentioning what the created workbook object represents or how it integrates with other tools (e.g., for subsequent operations).

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 significant meaning beyond the input schema, which has 0% description coverage. It explains that 'session_id' is for 'creating workbook in existing session' and is optional, while 'filepath' is 'legacy, deprecated' and provides usage recommendations. This compensates well for the schema's lack of descriptions, though it doesn't detail format requirements (e.g., path syntax).

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 ('Create') and resource ('new Excel workbook'), making the purpose immediately understandable. It distinguishes this tool from siblings like 'open_workbook' (which opens existing files) and 'list_workbooks' (which lists existing ones), though it doesn't explicitly mention these alternatives in the description itself.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear guidance on parameter usage ('Use session_id for better performance. filepath parameter is deprecated'), which helps the agent understand when to use which parameter. However, it doesn't explicitly state when to use this tool versus alternatives like 'open_workbook' for existing files or provide broader context about when creation is appropriate.

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