Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

open_workbook

Open an Excel workbook to create a session for data manipulation, formatting, and worksheet management through native Excel integration.

Instructions

Open an Excel workbook and create a session.

Args:
    filepath: Path to Excel file
    visible: Whether to show Excel window (default: False)
    read_only: Whether to open in read-only mode (default: False)
    
Returns:
    Dictionary with session_id, filepath, visible, read_only, and sheets

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes
visibleNo
read_onlyNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool registration and handler for 'open_workbook'. Handles input validation, path resolution via get_excel_path, delegates to SESSION_MANAGER.open_workbook, retrieves session info and returns structured response with session details.
    @mcp.tool()
    def open_workbook(
        filepath: str,
        visible: bool = False,
        read_only: bool = False
    ) -> Dict[str, Any]:
        """
        Open an Excel workbook and create a session.
        
        Args:
            filepath: Path to Excel file
            visible: Whether to show Excel window (default: False)
            read_only: Whether to open in read-only mode (default: False)
            
        Returns:
            Dictionary with session_id, filepath, visible, read_only, and sheets
        """
        try:
            full_path = get_excel_path(filepath)
            session_id = SESSION_MANAGER.open_workbook(full_path, visible, read_only)
            
            # Get session info
            session = SESSION_MANAGER.get_session(session_id)
            if not session:
                raise WorkbookError(f"Failed to create session for {filepath}")
            
            return {
                "session_id": session_id,
                "filepath": session.filepath,
                "visible": session.visible,
                "read_only": session.read_only,
                "sheets": [sheet.name for sheet in session.workbook.sheets]
            }
            
        except Exception as e:
            logger.error(f"Error opening workbook: {e}")
            raise WorkbookError(f"Failed to open workbook: {str(e)}")
  • Core implementation of workbook opening in ExcelSessionManager.open_workbook. Manages session limits (LRU eviction), COM initialization, Excel app creation, file locking checks, workbook opening/creation, session object creation and storage, with proper error handling and cleanup.
    def open_workbook(self, filepath: str, visible: bool = False,
                     read_only: bool = False) -> str:
        """Open a workbook and create a new session"""
    
        # Generate session ID
        session_id = str(uuid.uuid4())
    
        # Check if we need to evict old sessions (LRU)
        with self._sessions_lock:
            if len(self._sessions) >= self._max_sessions:
                self._evict_lru_session()
    
        # Ensure COM is initialized for this thread (needed for auto-recovery in worker threads)
        _com_initialize()
    
        try:
            # Log session creation
            logger.debug(f"Creating session {session_id} for {filepath} (visible={visible}, read_only={read_only})")
    
            # Create Excel app instance
            app = xw.App(visible=visible, add_book=False)
            app.display_alerts = False
            app.screen_updating = not visible  # Disable screen updating for hidden instances
            
            # Open workbook
            abs_path = os.path.abspath(filepath)
            
            if os.path.exists(abs_path):
                # Check if file is locked before trying to open
                if not read_only and is_file_locked(abs_path):
                    app.quit()  # Clean up the app we just created
                    raise IOError(f"FILE_ACCESS_ERROR: '{abs_path}' is locked by another process. Use force_close_workbook_by_path() to force close it first.")
                
                wb = app.books.open(abs_path, read_only=read_only)
                logger.debug(f"Opened existing workbook: {abs_path}")
            else:
                # Create new workbook if doesn't exist
                wb = app.books.add()
                Path(abs_path).parent.mkdir(parents=True, exist_ok=True)
                wb.save(abs_path)
                logger.debug(f"Created new workbook: {abs_path}")
            
            # Create session
            session = ExcelSession(session_id, abs_path, app, wb, visible, read_only)
            
            # Store session
            with self._sessions_lock:
                self._sessions[session_id] = session
                logger.info(f"Session {session_id} created for {filepath} (total sessions: {len(self._sessions)})")
            
            return session_id
            
        except Exception as e:
            logger.error(f"Failed to create session for {filepath}: {e}")
            # Clean up on failure
            if 'app' in locals():
                try:
                    app.quit()
                except:
                    pass
            raise
  • Import of global SESSION_MANAGER singleton used by the open_workbook tool handler.
    from xlwings_mcp.session import SESSION_MANAGER
    from xlwings_mcp.force_close import force_close_workbook_by_path
  • Helper function to resolve relative filepaths to absolute paths based on SSE mode configuration.
    def get_excel_path(filename: str) -> str:
        """Get full path to Excel file.
        
        Args:
            filename: Name of Excel file
            
        Returns:
            Full path to Excel file
        """
        # If filename is already an absolute path, return it
        if os.path.isabs(filename):
            return filename
    
        # Check if in SSE mode (EXCEL_FILES_PATH is not None)
        if EXCEL_FILES_PATH is None:
            # Must use absolute path
            raise ValueError(f"Invalid filename: {filename}, must be an absolute path when not in SSE mode")
    
        # In SSE mode, if it's a relative path, resolve it based on EXCEL_FILES_PATH
        return os.path.join(EXCEL_FILES_PATH, filename)

Schema Changelog

Changes observed during successful MCP inspections.

  1. Added

TDQS

B3.2/5.0
Behavior2/5

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

The description mentions 'create a session' but does not explain what a session entails (e.g., duration, locking, concurrency limits). No annotations are provided, so the description carries the full burden but fails to disclose key behavioral traits like mutability or error conditions.

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 a clear docstring format (Args, Returns). The first sentence effectively summarizes the tool. Minor repetition of default values already in the schema.

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 no annotations and an output schema that documents return values, the description covers basics but misses important context like session management, concurrency issues, and error handling. It is adequate but not comprehensive.

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?

With 0% schema coverage, the description compensates by explaining each parameter's purpose (filepath, visible, read_only) beyond type/default. However, it lacks details like acceptable file path formats or implications of read_only on editing.

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 clearly states it opens an Excel workbook and creates a session, distinguishing it from sibling tools like create_workbook (creates new) and close_workbook (closes). The verb+resource is specific and unambiguous.

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 such as create_workbook or read_data_from_excel. It does not mention prerequisites, file state (e.g., already open), or conditions for optimal use.

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