Skip to main content
Glama
akuntumbabanget-sketch

Ultimate Excel MCP Server

README.md
<div align="center">
  <img src="docs/banner.png" alt="Ultimate Excel MCP Server Banner" width="100%">

  <h1>🚀 Ultimate Excel MCP Server</h1>
  <p><strong>A hyper-advanced Model Context Protocol (MCP) Server for real-time AI control over Microsoft Excel.</strong></p>

  [![Python Version](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
  [![FastAPI](https://img.shields.io/badge/FastAPI-0.100%2B-green.svg)](https://fastapi.tiangolo.com/)
  [![React](https://img.shields.io/badge/React-18.0%2B-61DAFB.svg)](https://reactjs.org/)
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

  <p>
    <a href="#features">Features</a> •
    <a href="#architecture">Architecture</a> •
    <a href="#installation">Installation</a> •
    <a href="#mcp-configuration">MCP Config</a> •
    <a href="#api--tools-reference">Tools</a> •
    <a href="#troubleshooting">Troubleshooting</a>
  </p>
</div>

---

## 📸 Screenshots

*(Replace these images with actual screenshots of your project before publishing)*

<div align="center">
  <img src="docs/screenshot-dashboard.png" alt="React Dashboard UI" width="48%">
  <img src="docs/screenshot-excel.png" alt="Live Excel AI Magic" width="48%">
  <p><em>Left: Real-time React Telemetry Dashboard. Right: AI generating a dashboard directly inside MS Excel.</em></p>
</div>

---

## 🌟 Introduction

Welcome to the **Ultimate Excel MCP Server**. This project bridges the gap between Advanced AI Agents (like Antigravity, Cursor, Claude) and your local Microsoft Excel application. By leveraging the **Model Context Protocol (MCP)**, this server allows AI to read, write, format, and execute complex VBA macros directly inside your active Excel window in real-time.

Gone are the days of AI generating Python scripts for you to run manually, or exporting `.csv` files. With this server, you type a prompt, and the AI builds a fully functional spreadsheet right before your eyes.

---

## 🔥 Features (Super OP)

1. **Live COM Integration**: Connects directly to your open Microsoft Excel window using `win32com`. No need to save or close files.
2. **Auto-Reconnection**: If you close Excel and open it again, the server gracefully handles the COM disconnection and reconnects on the next polling cycle.
3. **VBA Macro Injection (`execute_vba_macro`)**: The most OP feature. Allows AI to write and execute VBA macros on the fly to generate charts, pivot tables, custom UserForms, and advanced UIs in under a second.
4. **Rich Formatting Control**: Change cell background colors, font colors, bold/italic styles, and borders dynamically.
5. **Offline Headless Mode**: Includes an `openpyxl` engine for reading and writing `.xlsx` files silently in the background when Excel is not open.
6. **Real-time React Dashboard**: A beautiful, dark-mode web dashboard built with Vite + React + Tailwind v4 that monitors the AI's actions and logs all tool executions live via Server-Sent Events (SSE).
7. **Zero JSON-RPC Corruption**: Specifically engineered with standard output (`stdout`) redirection to `stderr` to prevent standard Python prints from breaking the MCP stdio protocol.

---

## 🏗️ Architecture & Flow

<div align="center">
  <img src="docs/architecture.png" alt="3D Architecture Render" width="80%">
</div>

The system is composed of three main layers that communicate asynchronously to ensure lightning-fast performance:

```mermaid
flowchart TB
    classDef client fill:#2d3748,stroke:#4fd1c5,stroke-width:2px,color:#fff
    classDef server fill:#2b6cb0,stroke:#63b3ed,stroke-width:2px,color:#fff
    classDef target fill:#276749,stroke:#68d391,stroke-width:2px,color:#fff
    classDef dashboard fill:#702459,stroke:#d53f8c,stroke-width:2px,color:#fff

    A([🧠 AI Agent IDE]):::client <-->|JSON-RPC via stdio| B(🐍 FastAPI MCP Server):::server
    
    subgraph Engine Layer
    B -->|PyWin32 COM API| C[(📊 Live MS Excel)]:::target
    B -->|OpenPyxl| D[(📁 Offline .xlsx)]:::target
    end

    B -.->|SSE Logs & Metrics| E[💻 React Web Dashboard]:::dashboard
    E -.->|Axios REST API| B
```

---

## 📂 Directory Structure

```text
excel-mcp-ai/
│
├── docs/                       # Project Images & Banners
├── mcp_server/                 # Python Backend
│   ├── main.py                 # FastAPI & MCP Entrypoint
│   ├── mcp_tools.py            # Definition of all 7 MCP Tools
│   ├── win32_engine.py         # Live COM controller for Excel
│   ├── offline_engine.py       # Openpyxl controller for files
│   ├── dashboard_api.py        # REST API & SSE for React
│   └── config.py               # Settings manager
│
├── dashboard/                  # React Frontend
│   ├── src/
│   │   ├── components/         # React Components
│   │   ├── App.tsx             # Main App
│   │   └── index.css           # Tailwind v4 directives
│   ├── package.json            
│   └── vite.config.ts          
│
├── requirements.txt            # Python dependencies
├── run.bat                     # Quick-start script for Windows
└── README.md                   # This file
```

---

## 🚀 Getting Started

### Prerequisites
- **Windows OS** (Required for COM API)
- **Microsoft Excel** installed and activated
- **Python 3.10+**
- **Node.js 18+** (For building the dashboard)

### 1. Installation

Clone the repository and set up the Python environment:

```powershell
# Clone repo
git clone https://github.com/yourusername/ultimate-excel-mcp.git
cd ultimate-excel-mcp

# Create Virtual Environment
python -m venv venv
.\venv\Scripts\Activate.ps1

# Install Dependencies
pip install -r requirements.txt
```

### 2. Build the Dashboard

```powershell
cd dashboard
npm install
npm run build
cd ..
```

### 3. Run the Server

To run the full suite (FastAPI Dashboard on Port 8000 + MCP stdio readiness):

```powershell
.\run.bat
```

> **Note:** Do NOT run `run.bat` in a restricted context. Allow PowerShell scripts if needed via `Set-ExecutionPolicy RemoteSigned`.

---

## ⚙️ MCP Configuration

To connect this server to your AI IDE (like Antigravity, Cursor, or Claude Desktop), you need to register it in your `mcp_config.json` file.

**Crucial Step**: Because the AI runs the command from arbitrary directories, you MUST set the `PYTHONPATH` environment variable so Python can resolve the `mcp_server` module.

Open your `mcp_config.json` and append:

```json
{
  "mcpServers": {
    "Excel": {
      "command": "C:\\path\\to\\your\\excel-mcp-ai\\venv\\Scripts\\python.exe",
      "args": [
        "-m",
        "mcp_server.main",
        "--stdio"
      ],
      "env": {
        "PYTHONPATH": "C:\\path\\to\\your\\excel-mcp-ai"
      }
    }
  }
}
```

*Replace `C:\\path\\to\\your\\excel-mcp-ai` with the absolute path to your cloned repository.*

---

## 🛠️ API & Tools Reference

The server exposes 7 powerful MCP tools to the AI.

### 1. `get_active_excel_status`
Checks if Excel is running and retrieves the name of the currently active workbook and sheet.
- **Parameters**: None
- **Returns**: JSON object with `connected`, `active_workbook`, `active_sheet`.
- **Note**: If Excel is open but no workbook is active, this tool will automatically create a Blank Workbook (`Workbooks.Add()`).

### 2. `write_active_excel_range`
Injects 2D array data into the active sheet.
- **Parameters**:
  - `range_address` (str): e.g. "A1:C10"
  - `data` (list of lists): The 2D array of data.
  - `sheet_name` (str, optional): Target sheet. Defaults to active.

### 3. `read_active_excel_range`
Reads data from the active Excel sheet.
- **Parameters**:
  - `range_address` (str): e.g. "A1:C10"
  - `sheet_name` (str, optional): Target sheet.

### 4. `format_active_excel_range`
Applies aesthetic styling to a specific range.
- **Parameters**:
  - `range_address` (str)
  - `options` (dict): 
    - `bg_color` (hex string, e.g., "#21A366")
    - `font_color` (hex string, e.g., "#FFFFFF")
    - `bold` (boolean)

### 5. `execute_vba_macro` (🌟 The OP Tool)
Injects and runs a Visual Basic for Applications (VBA) macro script directly in memory.
- **Parameters**:
  - `macro_code` (str): The full VBA code (e.g., `Sub MyMacro() ... End Sub`)
  - `macro_name` (str): The name of the subroutine to execute.
- **Use Cases**: Creating charts, generating pivot tables, turning off gridlines, conditional formatting, adding interactive buttons.

### 6. `read_offline_excel`
Reads data from a `.xlsx` file on disk using `openpyxl` without opening MS Excel.
- **Parameters**: `file_path`, `range_address`, `sheet_name`.

### 7. `write_offline_excel`
Writes data to a `.xlsx` file on disk silently.
- **Parameters**: `file_path`, `range_address`, `data`, `sheet_name`.

---

## 🤖 Prompts & AI Agent Skills

To maximize the potential of this server, you can give your AI specific "Skills". Here is an example of an **OP Prompt** you can feed to the AI:

> "Build a completely automated Employee Attendance Dashboard. Use `execute_vba_macro` to create a new sheet called 'Dashboard', remove the gridlines, and insert a dark-blue header. Populate 15 lines of dummy attendance data with dynamic formulas computing the attendance percentage. Add a Bar Chart using VBA next to the table to visualize the data, and add a Macro-enabled 'Refresh' button."

The AI will parse this, write a complete VBA script on the fly, pass it to `execute_vba_macro`, and your Excel window will transform instantly.

---

## 🛡️ Trust Center Security Settings

For the `execute_vba_macro` tool to work, Microsoft Excel must allow programmatic access to the VBA object model.

1. Open Excel.
2. Go to **File > Options > Trust Center > Trust Center Settings**.
3. Select **Macro Settings**.
4. Check the box: **☑ Trust access to the VBA project object model**.
5. Click OK.

---

## 🔧 Troubleshooting

### 1. `invalid character 'I' looking for beginning of value`
This error occurs in the IDE when the Python MCP server prints standard console text (like `INFO: Server started`) to `stdout`. The MCP protocol requires `stdout` to be strictly JSON.
**Fix**: We have already routed all `print()` statements to `sys.stderr` in `main.py` and `win32_engine.py`. If you add custom prints, ensure you add `, file=sys.stderr`.

### 2. `NameError: name 'CORSMiddleware' is not defined`
Ensure that your `main.py` has the following import:
```python
from fastapi.middleware.cors import CORSMiddleware
```

### 3. `ModuleNotFoundError: No module named 'mcp_server'`
Your AI IDE is executing the Python module from a different directory. You MUST set `"env": { "PYTHONPATH": "..." }` in your `mcp_config.json` as shown in the Configuration section.

### 4. `COM Error: 'str' object is not callable`
This happens in pywin32 when you try to call a property as a method. For example, `ActiveCell.Address` is a string in Python, not a callable function like it is in VBA. The backend handles this gracefully.

### 5. `pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.')`
Because FastAPI routes run on separate async threads, `win32com` requires COM to be initialized on every thread. The `win32_engine.py` calls `pythoncom.CoInitialize()` at the start of every connection cycle to prevent this.

---

## 🤝 Contributing

Contributions make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.

1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

---

## 📜 License

Distributed under the MIT License. See `LICENSE` for more information.

---
<div align="center">
  <i>Built with ❤️ for the AI Automation community.</i>
</div>

Maintenance

ActivitySlowing
ResponsivenessNo issues