Skip to main content
Glama

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.


Related MCP server: Aspose.Cells Cloud MCP Server

🏗️ 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:

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 (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:

    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:

    cp .env.example .env

    Edita .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:

{
  "mcpServers": {
    "excel-o365": {
      "command": "uv",
      "args": [
        "--directory",
        "/ruta/a/excel-mcp-toolbox",
        "run",
        "excel-mcp"
      ]
    }
  }
}

🧪 Pruebas

Para ejecutar la suite de pruebas unitarias:

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:

    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:

    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:

    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:

./deploy.sh

📄 Licencia

Este proyecto está licenciado bajo los términos de la Licencia Apache 2.0. Consulta el archivo LICENSE para más información.

Available Tools

6 tools
excel_add_table_rowsExcel Add Table RowsB
Read-only

Append one or more rows of data into an existing Excel table.

Inputs: rows (required), worksheet_name (required), item_id_or_path (required), table_name_or_id (required), +3 more. Returns: result

excel_add_worksheetExcel Add WorksheetB
Read-only

Add a new worksheet/tab to an existing Excel workbook.

Inputs: worksheet_name (required), item_id_or_path (required), site_id, drive_id. Returns: result

excel_create_tableExcel Create TableC
Read-only

Create a structured table within a range of an Excel worksheet.

Inputs: address (required), worksheet_name (required), item_id_or_path (required), site_id, +3 more. Returns: result

excel_create_workbookExcel Create WorkbookB
Read-only

Create a new Excel workbook (.xlsx) in OneDrive or SharePoint.

Inputs: filename (required), site_id, drive_id, folder_path. Returns: result

excel_get_table_rowsExcel Get Table RowsA
Read-only

Get column headers and data rows from an existing Excel table.

Inputs: worksheet_name (required), item_id_or_path (required), table_name_or_id (required), site_id, +1 more. Returns: result

excel_list_workbooksExcel List WorkbooksA
Read-only

List Excel workbooks (.xlsx, .xls) in a target OneDrive or SharePoint folder.

Inputs: site_id, drive_id, folder_path. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 6 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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.

    Related MCP Connectors

    Related MCP Servers