excel-o365
# Excel Office 365 MCP Toolbox
Un servidor MCP (Model Context Protocol) desarrollado en Python con **FastMCP** para gestionar archivos de Microsoft Excel en Office 365 (OneDrive / SharePoint) a través de **Microsoft Graph API**.
## 🚀 Características
- **Crear libros de Excel (`.xlsx`)**: Crea archivos nuevos en OneDrive o SharePoint.
- **Listar libros de Excel**: Explora y lista archivos `.xlsx` en carpetas.
- **Agregar hojas de trabajo**: Añade nuevas pestañas a un libro existente.
- **Crear tablas**: Convierte rangos en tablas estructuradas con encabezados.
- **Agregar filas a tablas**: Inserta/añade nuevas filas de datos a una tabla de Excel.
- **Leer filas de tablas**: Extrae encabezados y filas de una tabla existente.
---
## 🏗️ Arquitectura de la Solución
El siguiente diagrama ilustra la arquitectura de componentes y el flujo de integración entre el servidor FastMCP en Python, Google Cloud Run, Microsoft Entra ID y Microsoft Graph API en Office 365:
```mermaid
flowchart TD
subgraph Server["⚡ Excel FastMCP Server (Python / FastMCP)"]
ServerCore["FastMCP Core (server.py)"]
subgraph Tools["🛠️ Herramientas MCP"]
WorkbooksTool["workbooks.py\n(excel_create_workbook, excel_list_workbooks)"]
SheetsTool["sheets.py\n(excel_add_worksheet)"]
TablesTool["tables.py\n(excel_create_table, excel_add_table_rows, excel_get_table_rows)"]
end
GraphClient["GraphExcelService (graph_client.py)\n- Plantilla In-Memory OpenXML XLSX\n- API Async REST Graph Client"]
AuthModule["Módulo de Autenticación (auth.py / config.py)\n- ClientSecretCredential (MSAL / Azure Identity)"]
end
subgraph CloudRunInfra["☁️ Infraestructura GCP (Cloud Run)"]
CloudRunService["Google Cloud Run (excel-mcp-toolbox)"]
SecretManager["GCP Secret Manager\n(MS_CLIENT_SECRET)"]
end
subgraph MS365["🏢 Microsoft 365 & Entra ID"]
EntraID["Microsoft Entra ID (Azure AD)\n- OAuth 2.0 Client Credentials"]
GraphAPI["Microsoft Graph API v1.0\n- /users/{target_email}/drive"]
Office365["OneDrive for Business / SharePoint"]
end
CloudRunService --> ServerCore
SecretManager -.->|"Inyecta MS_CLIENT_SECRET"| AuthModule
ServerCore --> Tools
Tools --> GraphClient
GraphClient --> AuthModule
AuthModule -->|"1. Solicita Token Bearer OAuth2"| EntraID
EntraID -->|"2. Token de Acceso (Files.ReadWrite.All)"| AuthModule
GraphClient -->|"3. Peticiones REST HTTPS"| GraphAPI
GraphAPI -->|"4. Persistencia de Libros (.xlsx)"| Office365
style Server fill:#e6f4ea,stroke:#34a853,stroke-width:2px
style Tools fill:#ffffff,stroke:#34a853,stroke-width:1px
style CloudRunInfra fill:#e8f0fe,stroke:#4285f4,stroke-width:2px
style MS365 fill:#fef7e0,stroke:#fbbc04,stroke-width:2px
```
### Componentes de la Arquitectura
1. **Servidor FastMCP (`excel-mcp-toolbox`)**:
* **`server.py`**: Punto de entrada que inicializa el servidor FastMCP e integra los módulos de herramientas.
* **`tools/`**: Expone las 6 herramientas atómicas con parámetros simplificados (`str` para listas y filas) y respuestas formateadas en JSON explícito.
* **`graph_client.py`**: Servicio asíncrono que genera la estructura OpenXML de un `.xlsx` en memoria mediante `zipfile` y realiza llamadas REST HTTPS a Microsoft Graph API.
* **`auth.py` & `config.py`**: Gestión de credenciales mediante `pydantic-settings` y autenticación OAuth 2.0 App-Only (`ClientSecretCredential`).
2. **Infraestructura en GCP (Cloud Run & Secret Manager)**:
* **Cloud Run**: Ejecuta el contenedor del servidor en un entorno serverless ligero (base `python:3.11-slim`).
* **Secret Manager**: Almacena de forma segura la credencial sensible `MS_CLIENT_SECRET`, inyectándola al contenedor en tiempo de ejecución.
3. **Microsoft 365 & Entra ID (Azure AD)**:
* **Entra ID**: Otorga permisos de aplicación `Files.ReadWrite.All` para interactuar con OneDrive/SharePoint del usuario destino (`TARGET_USER_EMAIL`).
* **Microsoft Graph API**: Procesa las operaciones de creación de archivos, pestañas, tablas y formateo de datos.
---
## 🛠️ Requisitos Previos
- Python 3.11+
- [uv](https://github.com/astral-sh/uv) (Gestor de paquetes de Python)
- Registro de Aplicación en **Microsoft Entra ID (Azure AD)** con permisos `Files.ReadWrite` o `Files.ReadWrite.All`.
---
## 📦 Configuración e Instalación
1. **Clonar e instalar dependencias:**
```bash
uv venv .venv
source .venv/bin/activate
uv pip install -e .
```
2. **Configurar variables de entorno (`.env`):**
Copia `.env.example` a `.env` y completa tus credenciales de Azure AD:
```bash
cp .env.example .env
```
Edita `.env`:
```env
MS_TENANT_ID=tu-tenant-id
MS_CLIENT_ID=tu-client-id
MS_CLIENT_SECRET=tu-client-secret
DEFAULT_DRIVE_TYPE=onedrive
```
---
## 🚦 Uso con Clientes MCP (Cursor, Claude Desktop, Antigravity)
Agrega la configuración del servidor a la sección de MCP servers de tu cliente:
```json
{
"mcpServers": {
"excel-o365": {
"command": "uv",
"args": [
"--directory",
"/ruta/a/excel-mcp-toolbox",
"run",
"excel-mcp"
]
}
}
}
```
---
## 🧪 Pruebas
Para ejecutar la suite de pruebas unitarias:
```bash
uv run pytest
```
---
## ☁️ Despliegue en Google Cloud Run
Este proyecto incluye soporte nativo para ejecutarse como un servicio de contenedor HTTP con **Streamable HTTP** (`streamable-http`) en **Google Cloud Run**.
### 1. Variables de Configuración
- **Proyecto GCP**: `tu-proyecto-gcp`
- **Región**: `us-central1`
- **Artifact Registry**: `containers`
- **Secret Manager**: `excel-mcp-client-secret`
- **Servicio Cloud Run**: `excel-mcp-toolbox`
### 2. Pasos de Despliegue Manuales con `gcloud`
1. **Guardar el secreto sensible en Secret Manager:**
```bash
gcloud secrets create excel-mcp-client-secret \
--replication-policy="automatic" \
--project="tu-proyecto-gcp"
echo -n "TU_MS_CLIENT_SECRET" | gcloud secrets versions add excel-mcp-client-secret \
--data-file=- \
--project="tu-proyecto-gcp"
```
2. **Compilar la imagen del contenedor con Cloud Build:**
```bash
gcloud builds submit \
--tag us-central1-docker.pkg.dev/tu-proyecto-gcp/containers/excel-mcp-toolbox:latest \
--project="tu-proyecto-gcp"
```
3. **Desplegar en Cloud Run:**
```bash
gcloud run deploy excel-mcp-toolbox \
--image us-central1-docker.pkg.dev/tu-proyecto-gcp/containers/excel-mcp-toolbox:latest \
--region us-central1 \
--project tu-proyecto-gcp \
--no-allow-unauthenticated \
--port 8080 \
--set-env-vars MS_TENANT_ID="tu-tenant-id",MS_CLIENT_ID="tu-client-id",TARGET_USER_EMAIL="usuario@tu-empresa.com" \
--set-secrets MS_CLIENT_SECRET=excel-mcp-client-secret:latest
```
### 3. Despliegue Automatizado
También puedes ejecutar el script ejecutable `./deploy.sh` cargando las variables desde tu archivo `.env`:
```bash
./deploy.sh
```
---
## 📄 Licencia
Este proyecto está licenciado bajo los términos de la **Licencia Apache 2.0**. Consulta el archivo [LICENSE](LICENSE) para más información.
TDQS
Scored across 6 tools
Each tool targets a distinct operation: listing workbooks, creating workbooks, creating tables, adding worksheets, appending rows, and reading rows. There is no overlap or ambiguity between them.
All tools follow a consistent excel_<verb>_<noun> pattern (list_workbooks, create_table, create_workbook, add_worksheet, add_table_rows, get_table_rows). The naming convention is uniform and predictable.
Six tools is well-scoped for an Excel/O365 server handling workbook and table operations. Each tool addresses a meaningful need without redundancy or bloat.
The core lifecycle of workbook creation, worksheet addition, table creation, row insertion, and row retrieval is covered. Minor gaps exist (no delete/update operations, no listing worksheets), but common workflows are supported.