Files
sbroenne__mcp-server-excel/README.md
T
Stefan Broenner df928e95f4 Refactor (#188)
* feat: align CLI with MCP Server session API pattern

MAJOR CHANGE: CLI now uses MCP-aligned session terminology
- Old: batch-begin, batch-commit, batch-list
- New: open, save, list (primary commands)
- Legacy batch commands still work but map to new session commands

IMPLEMENTATION:
✓ BatchCommands: Renamed Begin() → Open(), Commit() → Save()
✓ Program.cs: Updated routing for new command names
✓ Program.cs: Added backward compatibility for old batch commands
✓ Program.cs: Updated help text to show session lifecycle
✓ Program.cs: Banner now says 'MCP-aligned Session API'
✓ CommandHelper: Updated --batch-id → --session-id parameter detection
✓ Error messages: Updated terminology from 'batch' to 'session'
✓ All file operations: Updated comments and output messages

BACKWARD COMPATIBILITY:
✓ Old batch-begin/batch-commit/batch-list commands still work
✓ --batch-id flag still accepted (mapped to --session-id internally)
✓ Both terminologies coexist during transition

TESTING:
✓ CLI builds: 0 warnings, 0 errors
✓ MCP smoke test passed
✓ Help text displays new session commands and deprecation notice

DOCUMENTATION:
✓ CLI README already updated in previous commit with session API examples
✓ Help output now clearly shows primary commands and deprecation path

This aligns the CLI completely with the MCP Server's session-based API,
making both interfaces consistent and simplifying user experience.

* feat: split save/close commands - save keeps session open, close discards changes

* refactor: remove backward compatibility layer - legacy GetBatch method and usage

* fix: improve Range command error messages - use RangeHelpers specific errors

- All Range operations now use RangeHelpers.ResolveRange() with specificError out parameter
- Instead of cryptic '0x800A03EC' COM error, users now get helpful messages like:
  * 'Sheet \\'Validation_Summary\\' not found. Available sheets: Sheet1, Sheet2'
  * 'Named range \\'Sales\\' not found. Available named ranges: Parameters, Region'
- Includes suggestions to use excel_worksheet or excel_namedrange tools
- Affects: Get/Set Values/Formulas, Copy, Clear, Insert, Delete, Find, Replace, Sort, Hyperlinks, NumberFormat operations

* fix: simplify COM error messages - remove LLM guidance

Removed verbose step-by-step guidance from error messages. LLMs don't need to be told what to do, just what failed.

Changed from:
  'This usually means: (1) Sheet doesn't exist, (2) Range invalid, or (3) Session not open.
   Use excel_worksheet(action: list) to verify...'

To:
  'Cannot read range X on sheet Y: Insufficient memory to continue the execution of the program'

Files changed:
- RangeCommands.Values.cs: Simplified GetValuesAsync and SetValuesAsync COM error messages
- RangeCommands.Formulas.cs: Simplified GetFormulasAsync and SetFormulasAsync COM error messages
- ExcelToolsBase.cs: Simplified session validation error - just state facts, no instructions

* docs: add error message style guidance - facts not instructions

Added Best Practice #9 and Error Message Style section to mcp-server-guide.

Key principle: Error messages should state facts (what failed, why), not prescribe solutions.
LLMs are intelligent agents that determine next steps - they don't need step-by-step guidance.

Example:
  ❌ Wrong: 'This usually means: (1) Sheet doesn't exist... Use excel_worksheet(list)...'
  ✅ Correct: 'Cannot read range X on sheet Y: Insufficient memory'

This matches the simplifications in commit 21d4c58.

* fix: return JSON errors from OpenSessionAsync instead of throwing

Changed OpenSessionAsync to catch exceptions from CreateSessionAsync and return JSON with success=false instead of letting them bubble up as unhandled exceptions.

Fixes the generic 'An error occurred invoking excel_file' message shown when file was already open or other session creation errors occurred.

Files changed:
- ExcelFileTool.cs: Wrapped CreateSessionAsync in try-catch, return JSON errors

* refactor: Replace McpException with standard .NET exceptions

CRITICAL INSIGHT (Phase 8): Discovered that McpException usage was unnecessary complexity.
Since we catch ALL exceptions before the MCP SDK sees them and return JSON responses,
the SDK never encounters McpException - it gets our JSON error response instead.

CHANGES:
- Removed McpException catch blocks from all 11 tool files
- Updated ExcelToolsBase to throw ArgumentException (validation) and InvalidOperationException (state)
- Replaced McpException throws in:
  * ExcelFileTool (5 throws)
  * ExcelConnectionTool (17 throws)
  * All 9 'unknown action' switch branches
  * ExcelWorksheetTool invalid visibility

ARCHITECTURAL BENEFIT:
- Removed unnecessary coupling to ModelContextProtocol.McpException
- Single catch (Exception ex) block now handles all cases
- Uses standard .NET exception types for clearer semantics:
  * ArgumentException for parameter validation
  * InvalidOperationException for invalid state
- Simpler, more idiomatic C# code
- Same error handling quality (descriptive JSON responses)

REMAINING:
- ~86 parameter validation throws still using McpException (will be caught as Exception)
- These still work correctly but should be migrated to ArgumentException in future PRs
- Build: 0 warnings, 0 errors

RATIONALE:
The MCP SDK wraps our tool invocations with try-catch. Our code catches exceptions
BEFORE the SDK sees them and returns JSON with isError=true. Therefore, whether we
throw McpException, ArgumentException, or any other Exception is irrelevant to the
SDK - it receives JSON in all cases. Using standard .NET exceptions is cleaner,
doesn't add SDK coupling, and makes the code more maintainable.

* refactor: Complete migration to ArgumentException for ALL parameter validations

Complete removal of McpException pattern across all 11 tool files:
- ExcelDataModelTool: 23 throws (all measure/table/relationship parameters)
- ExcelWorksheetTool: 16 throws (all sheet/color/visibility parameters)
- ExcelVbaTool: 10 throws (all module/path parameters)
- ExcelTableTool: 5 throws (all table/column/format parameters)
- ExcelQueryTableTool: 10 throws (all query table parameters)
- ExcelRangeTool: 2 throws (shift direction validation)
- ExcelPivotTableTool: 4 throws (aggregation/sort direction validation)
- ExcelPowerQueryTool: 12 throws (completed in prior batch)
- ExcelNamedRangeTool: 9 throws (completed in prior batch)
- ExcelConnectionTool: 17 throws (completed in prior batch)
- ExcelFileTool: 5 throws (completed in prior batch)

TOTAL MIGRATION: 117/~117 parameter validation throws replaced

Architecture Insight:
- Standard .NET exceptions (ArgumentException for invalid input)
- Single catch (Exception ex) block handles all cases
- No SDK coupling - clean separation of concerns
- Build: 0 warnings, 0 errors (maintained throughout)

Breaking Simplification:
- Removed unnecessary McpException abstraction layer
- SDK-side exception handling wraps all tool invocations
- No behavior change to callers (still returns JSON with isError=true)
- Cleaner, more maintainable code with standard .NET patterns

* refactor: Simplify async command invocation by removing unnecessary lambda expressions

* fix: update .gitignore to exclude Jekyll generated files

* Fix MCP Server tests: tool discovery and enum completeness

- Fixed ToolDiscoveryTests: Removed non-existent 'excel_batch' from expected tools list
- Fixed ActionEnumCompletenessTests: Added FileAction.Open/Save/Close mappings to ActionExtensions
- Fixed tool naming: Changed 'excel_conditional_format' to 'excel_conditionalformat' (matches naming convention)
- Enum cleanup: Removed unused BatchAction enum and its ToActionString() mapping

Test results: 60 passing (was 58), 9 failing (was 11)
Remaining failures are pre-existing issues (Power Query COM errors, invalid session handling)

* Update documentation: 12 tools with 168 operations

- Added excel_conditionalformat tool (2 actions: add-rule, clear-rules)
- Removed excel_batch from tool lists (doesn't exist)
- Updated operation counts: 166 → 168
- Updated tool counts: 11 → 12
- Added conditional formatting examples to CLI README
- Updated all READMEs: main, MCP Server, CLI, VS Code extension, GitHub pages
- Updated range action counts: 45 → 43 (moved conditional formatting to dedicated tool)
- Added excel_querytable (8 actions) to complete tool list
- Updated excel_file action count: 3 → 6 (open, save, close, create-empty, close-workbook, test)

* Delete incorrect MCP Server tests expecting exceptions

Removed tests that expected McpException for invalid sessions/missing parameters.
Per CRITICAL-RULES.md Rule 17, MCP tools should return JSON with success=false
for business errors, NOT throw exceptions.

Tests deleted:
- DetailedErrorMessageTests.cs (entire file - 8 tests)
- ExcelMcpServerTests.ExcelWorksheet_InvalidSession_ShouldThrowError

Test results: 59 passing (was 60), 2 failing (was 9)
Remaining 2 failures are legitimate Power Query COM errors (RPC failures)

* Fix ExcelBatch async disposal and timeout handling

- Replace synchronous Task.Wait() with async DisposeAsync pattern
- Add proper CancellationTokenSource disposal in finally blocks
- Use ConfigureAwait(false) for library code
- Fix timeout handling to properly cancel operations
- Add comprehensive disposal tests with timeout scenarios

* Remove ExportAsync methods - consolidate with ViewAsync

All three command types (PowerQuery, VBA, Connection) now use ViewAsync
instead of ExportAsync to return code/data directly rather than writing
to files. This simplifies the API by eliminating duplicate functionality.

Changes:
- Removed ExportAsync from IPowerQueryCommands, IVbaCommands, IConnectionCommands interfaces
- Removed ExportAsync implementations from all three command files
- Updated CLI commands to use ViewAsync instead (return code directly)
- Updated MCP Server tools to use ViewAsync instead (return JSON with code)
- Updated VBA test to use ViewAsync instead of ExportAsync
- Updated POWERQUERY-FUTURE-STATE-SPEC.md to remove ExportAsync references

Tests now verify code is returned in ViewAsync result rather than written to file.

* WIP: CLI async-to-sync conversion attempt - reverting to clean state

* Save WIP

* Align MCP tooling with updated actions

* - Refactored tools to reduce cognizant load on LLM
- Fix stability issues when working on multiple files at the same time

* Increase STA thread cleanup timeout from 3 to 10 seconds to prevent potential deadlocks during disposal

* Refactor QueryTable handling to use unified PowerQueryHelpers

- Updated QueryTableCommand to utilize PowerQueryHelpers for creating QueryTables.
- Introduced ConnectionHelpers for retrieving connection strings and command texts.
- Consolidated QueryTable creation options into PowerQueryHelpers.QueryTableCreateOptions.
- Removed redundant methods and classes related to QueryTable options.
- Enhanced error handling and validation for connection strings.
- Updated tests to reflect changes in QueryTable creation and options application.

* Revert "Refactor QueryTable handling to use unified PowerQueryHelpers"

This reverts commit 3603afcb71.

* Switch PowerQuery flows to inline M code

* Fix formula string formatting in JSON deserialization tests

* Fix test failures: formula syntax, PowerQuery Update, and QueryTable API usage

- Fixed JSON syntax in formula tests (removed extra quotes in array)
- Fixed raw string literal quote handling in Excel formulas
- Fixed PowerQuery Update to preserve worksheet data:
  * Capture QueryTable destination and ResultRange before deletion
  * Clear only ResultRange (not entire sheet)
  * Recreate at same location with clearEntireSheet: false
  * Eliminates legacy clearEntireSheet anti-pattern
- Fixed QueryTable tests to pass M code directly instead of file paths:
  * Removed file I/O operations (7 occurrences)
  * Aligned with PowerQueryCommands.Create() API signature

All 9 originally failing tests now pass (2 formula + 7 QueryTable/PowerQuery).

* Include mcp.json in version control

- Added .vscode/mcp.json to .gitignore exceptions
- Tracks MCP server configuration for project

* Add sheet movement and cross-workbook operations: Move, CopyToWorkbook, MoveToWorkbook
2025-11-17 09:27:59 +00:00

20 KiB

ExcelMcp - MCP Server for Microsoft Excel

Build MCP Server Build CLI Release Downloads

MCP Registry NuGet MCP Server NuGet CLI NuGet Core NuGet ComInterop

License: MIT .NET Platform Built with Copilot

Automate Excel with AI - A Model Context Protocol (MCP) server for comprehensive Excel automation through conversational AI.

ExcelMcp is a comprehensive Excel automation toolkit with two interfaces:

  1. MCP Server: Enables AI assistants (GitHub Copilot, Claude, ChatGPT) to automate Excel through natural language commands
  2. CLI Tool: Provides direct command-line control for scripting, RPA, and CI/CD workflows

Both share the same core functionality: automate Power Query, DAX measures, VBA macros, PivotTables, formatting, and data transformations. Choose MCP for AI-powered conversations or CLI for programmatic control - no Excel programming knowledge required. Built on Excel's native COM API for zero risk of file corruption.

💡 Interactive Development: Unlike file-based tools, ExcelMcp lets you see results instantly in Excel - create a query, run it, inspect the output, refine and repeat. Excel becomes your interactive workspace for rapid development and testing.

🤔 What is This?

Use natural language OR command-line to automate complex Excel tasks - your choice.

Stop manually clicking through Excel menus for repetitive tasks. Instead, describe what you want in plain English:

Data Transformation & Analysis:

  • "Optimize all my Power Queries in this workbook for better performance"
  • "Create a PivotTable from SalesData table showing top 10 products by region with sum and average"
  • "Build a DAX measure calculating year-over-year growth with proper time intelligence"

Formatting & Styling (No Programming Required):

  • "Format the revenue columns as currency, make headers bold with blue background, and add borders to the table"
  • "Apply conditional formatting to highlight values above $10,000 in red and below $5,000 in yellow"
  • "Convert this data range to an Excel Table with style TableStyleMedium2, add auto-filters, and create a totals row"

Workflow Automation:

  • "Find all cells containing 'Q1 2024' and replace with 'Q1 2025', then sort the table by Date descending"
  • "Add data validation dropdowns to the Status column with options: Active, Pending, Completed"
  • "Merge the header cells, center-align them, and auto-fit all column widths to content"

The AI assistant analyzes your request, generates the proper Excel automation commands, and executes them directly in your Excel application - no formulas or programming knowledge required.

Real-World Example - Power Query Optimization:

You: "This Power Query is taking 5 minutes to refresh. Can you optimize it?"

AI Assistant (using ExcelMcp):
1. Exports the M code to analyze performance bottlenecks
2. Identifies queries that can use query folding
3. Refactors the M code to push operations to the data source
4. Updates the query in your workbook
5. Tests the refresh (now completes in 30 seconds)

Result: A professionally optimized Power Query with documented improvements

🛡️ 100% Safe - Uses Excel's Native COM API

Unlike third-party libraries that manipulate .xlsx files directly (risking file corruption), ExcelMcp uses Excel's official COM API. This ensures:

  • ✅ Zero risk of document corruption - Excel handles all file operations safely
  • ✅ Interactive development - See changes in real-time, create → test → refine → iterate instantly
  • ✅ Comprehensive automation - Currently supports 168 operations across 12 specialized tools covering Power Query, Data Model/DAX, VBA, PivotTables, Excel Tables, ranges, conditional formatting, and more

💻 For Developers: Think of Excel as an AI-powered REPL - write code (Power Query M, DAX, VBA), execute instantly, inspect results visually in the live workbook. No more blind editing of .xlsx files.

🔧 Advanced Features:

  • Batch Operations - Group multiple operations in a single Excel session for 75-90% faster execution
  • Progress Logging - Real-time operation status updates via stderr (MCP protocol compatible)
  • Error Recovery - Intelligent retry suggestions and operation-specific troubleshooting guidance

👥 Who Should Use This?

Perfect for:

  • ✅ Data analysts automating repetitive Excel workflows
  • ✅ Developers building Excel-based data solutions
  • ✅ Business users managing complex Excel workbooks
  • ✅ Teams maintaining Power Query/VBA/DAX code in Git

Not suitable for:

  • ❌ Server-side data processing (use libraries like ClosedXML, EPPlus instead)
  • ❌ Linux/macOS users (Windows + Excel installation required)
  • ❌ High-volume batch operations (consider Excel-free alternatives)

🎯 What You Can Do

Development & Automation:

  • 🔄 Power Query - 16 operations: atomic workflows (create, update-and-refresh, refresh-all), manage transformations, load configurations (worksheet, data model, connection only), error diagnostics, M code evaluation
  • 📊 Power Pivot (Data Model) - 15 operations: build DAX measures, manage relationships, discover model structure (tables, columns), export to .dax files
  • 🎨 Excel Tables - 26 operations: automate formatting, filtering, sorting, structured references, number formats, column management
  • 📈 PivotTables - 20 operations: create and configure PivotTables for interactive analysis
  • 📝 VBA Macros - 7 operations: export/import/run VBA code, integrate with version control
  • 📋 Ranges & Data - 45 operations: values, formulas, copy/paste, find/replace, formatting, validation, merge, conditional formatting, cell protection
  • 📄 Worksheets - 13 operations: lifecycle management, tab colors, visibility controls
  • 🔌 Connections - 11 operations: manage OLEDB, ODBC, Text, Web data sources
  • 🏷️ Named Ranges - 7 operations: named range management and bulk operations
📚 See Complete Feature List (100+ Operations)

Power Query & M Code (16 operations)

✨ NEW: Atomic Operations - Single-call workflows replace multi-step patterns:

  • Create - Import + load in one operation (replaces import → load workflow)
  • Update & Refresh - Update M code + refresh data atomically
  • Refresh All - Batch refresh all queries in workbook
  • Update M Code - Stage code changes without refreshing data
  • Unload - Convert loaded query to connection-only

Core Operations:

  • Create, read, update, delete Power Query transformations
  • Export/import M code for version control
  • Manage query load destinations (worksheet/data model/connection-only/both)
  • Set privacy levels for data source combinations
  • Get load configuration for existing queries
  • Error diagnostics and M code evaluation
  • List Excel workbook sources for Power Query integration

Data Model & DAX (Power Pivot) (15 operations)

  • Create/update/delete DAX measures with format types (Currency, Percentage, Decimal, General)
  • Manage table relationships (create, toggle active/inactive, delete)
  • Discover model structure (tables, columns, measures, relationships)
  • Export measures to .dax files for Git workflows
  • Get comprehensive model information
  • Note: DAX calculated columns are not supported (use Excel UI for calculated columns)

Excel Tables (ListObjects) (26 operations)

  • Lifecycle: create, resize, rename, delete, get info
  • Styling: apply table styles, toggle totals row, set column totals
  • Column management: add, remove, rename columns
  • Data operations: append rows, apply filters (criteria/values), clear filters, get filter state
  • Sorting: single-column sort, multi-column sort (up to 3 levels)
  • Number formatting: get/set column number formats
  • Advanced features: structured references, Data Model integration

PivotTables (20 operations)

  • Creation: create from ranges or Excel Tables
  • Field management: add/remove fields to Row, Column, Value, Filter areas
  • Aggregation functions: Sum, Average, Count, Min, Max, etc. with validation
  • Advanced features: field filters, sorting, custom field names, number formatting
  • Data extraction: get PivotTable data as 2D arrays for further analysis
  • Lifecycle: list, get info, delete, refresh

VBA Macros (7 operations)

  • List all VBA modules and procedures
  • View module code without exporting
  • Export/import VBA modules to/from files
  • Update existing modules
  • Execute macros with parameters
  • Delete modules
  • Version control VBA code through file exports

Ranges & Worksheets

  • Data Operations (10 actions): get/set values/formulas, clear (all/contents/formats), copy/paste (all/values/formulas), insert/delete rows/columns/cells, find/replace, sort
  • Number Formatting (3 actions): get formats as 2D arrays, apply uniform format, set individual cell formats
  • Visual Formatting (1 action): font (name, size, bold, italic, underline, color), fill color, borders (style, weight, color), alignment (horizontal, vertical, wrap text, orientation)
  • Data Validation (3 actions): add validation rules (dropdowns, number/date/text rules), get validation info, remove validation
  • Hyperlinks (4 actions): add, remove, list all, get specific hyperlink
  • Smart Range Operations (3 actions): UsedRange, CurrentRegion, get range info (address, dimensions, format)
  • Merge Operations (3 actions): merge cells, unmerge cells, get merge info
  • Auto-Sizing (2 actions): auto-fit columns, auto-fit rows
  • Conditional Formatting (2 actions): add conditional formatting, clear conditional formatting
  • Cell Protection (2 actions): set cell lock status, get cell lock status
  • Formatting & Styling (3 actions): get style, set style, format range
  • 45 range operations total covering all common Excel range manipulation needs
  • Worksheet management (13 actions): lifecycle (create, rename, copy, delete), tab colors (set, get, clear), visibility controls (show, hide, very-hide, get/set status)

Data Connections (11 operations)

  • Manage OLEDB, ODBC, Text, Web connections
  • Import/export connections via .odc files
  • Update connection strings and properties
  • Refresh connections and test connectivity
  • Load connection-only connections to worksheet tables
  • Get/set connection properties (refresh settings, background query, etc.)

Named Ranges (7 operations)

  • List all named ranges with references
  • Get/set single values
  • Create/delete named ranges
  • Update cell references
  • Bulk create multiple parameters

🚀 Quick Start (2 Minutes)

Requirements: Windows OS + Microsoft Excel 2016+

⚠️ Important: Close all Excel files before using ExcelMcp. The server requires exclusive access to workbooks during automation (Excel COM limitation).

Fastest way to get started - everything configured automatically:

  1. Install Extension

    • Open VS Code → Extensions (Ctrl+Shift+X)
    • Search for "ExcelMcp"
    • Click Install
  2. Automatic Setup (no manual steps!)

    • ✅ Installs .NET 8 runtime
    • ✅ Includes bundled MCP server
    • ✅ Registers with AI assistants
    • ✅ Shows quick start guide
  3. Start Using It

    The extension opens automatically after installation with a quick start guide!


Manual Installation (Advanced Users)

For non-VS Code environments or manual setup:

# Install .NET 8 SDK
winget install Microsoft.DotNet.SDK.8

# Install ExcelMcp MCP server as a global tool
dotnet tool install --global Sbroenne.ExcelMcp.McpServer

# To update to the latest version later:
dotnet tool update --global Sbroenne.ExcelMcp.McpServer

Configure Your AI Assistant

ExcelMcp works with multiple AI coding assistants. Choose your setup:

🎯 Quick Setup: Ready-to-use config files → examples/mcp-configs/

For GitHub Copilot in VS Code - Create .vscode/mcp.json in your workspace:

{
  "servers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

For GitHub Copilot in Visual Studio - Create .mcp.json in your solution directory or %USERPROFILE%\.mcp.json:

{
  "servers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

For Claude Desktop - Edit %APPDATA%\Claude\claude_desktop_config.json:

{
  "mcpServers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

For Cursor - Add to settings or %APPDATA%\Cursor\User\globalStorage\mcp\mcp.json:

{
  "mcpServers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

For Cline (VS Code Extension) - Use the MCP settings panel in Cline or edit settings:

{
  "mcpServers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

For Windsurf - Add to MCP servers configuration:

{
  "mcpServers": {
    "excel": {
      "command": "dotnet",
      "args": ["tool", "run", "mcp-excel"]
    }
  }
}

📖 Detailed setup for each client: Installation Guide

Test It Out

Try a practical example - ask your AI assistant:

Create an empty Excel file called "test.xlsx" and add a Power Query that loads data from a CSV file

The AI will guide you through the process and execute the commands directly!


🔧 How It Works - COM Interop Architecture

ExcelMcp uses Windows COM automation to control the actual Excel application (not just .xlsx files).

This means you get:

  • ✅ Full Excel Feature Access - Power Query engine, VBA runtime, Data Model, calculation engine, pivot tables
  • ✅ True Compatibility - Works exactly like Excel UI, no feature limitations
  • ✅ Live Data Operations - Refresh Power Query, connections, Data Model in real workbooks
  • ✅ Interactive Development - Immediate Excel feedback as AI makes changes
  • ✅ All File Formats - .xlsx, .xlsm, .xlsb, even legacy formats

Technical Requirements:

  • ⚠️ Windows Only - COM interop is Windows-specific
  • ⚠️ Excel Required - Microsoft Excel 2016 or later must be installed
  • ⚠️ Desktop Environment - Controls actual Excel process (not for server-side processing)

🔟 MCP Tools Overview

12 specialized tools for comprehensive Excel automation:

  1. excel_powerquery (16 actions) - Power Query M code: create, view, import, export, update, delete, manage load destinations, privacy levels, errors, eval, list Excel sources, and place QueryTables precisely with targetCellAddress
  2. excel_datamodel (15 actions) - Power Pivot (Data Model): CRUD DAX measures/relationships, discover structure (tables, columns), export to .dax files
  3. excel_table (26 actions) - Excel Tables: lifecycle, columns, filters, sorts, structured references, totals, number formatting, Data Model integration
  4. excel_pivottable (20 actions) - PivotTables: create from ranges/tables, field management (row/column/value/filter), aggregations, filters, sorting, extract data
  5. excel_range (43 actions) - Ranges: get/set values/formulas, number formatting, visual formatting (font, fill, border, alignment), data validation, clear, copy, insert/delete, find/replace, sort, hyperlinks, merge, cell protection
  6. excel_conditionalformat (2 actions) - Conditional Formatting: add rules (cell value, expression-based), clear rules
  7. excel_vba (7 actions) - VBA: list, view, export, import, update, run, delete modules
  8. excel_connection (11 actions) - Connections: OLEDB/ODBC/Text/Web management, properties, refresh, test
  9. excel_worksheet (13 actions) - Worksheets: lifecycle (list, create, rename, copy, delete), tab colors (set-tab-color, get-tab-color, clear-tab-color), visibility (set-visibility, get-visibility, show, hide, very-hide)
  10. excel_namedrange (7 actions) - Named ranges: list, get, set, create, create-bulk, delete, update
  11. excel_querytable (8 actions) - QueryTables: create from connections/queries, refresh, update properties, delete
  12. excel_file (6 actions) - File operations: create empty, open, save, close, close-workbook, test

Total: 12 tools with 168 actions

📚 Complete MCP Server Guide → - Detailed tool documentation and examples


📋 Additional Information

Testing Philosophy

Why No Unit Tests? ExcelMcp uses integration tests exclusively because Excel COM cannot be meaningfully mocked. Our integration tests ARE our unit tests. See ADR-001: No Unit Tests for full architectural rationale.

CLI for Direct Automation

ExcelMcp also provides a command-line interface for Excel automation (no AI required). Run excelcli --help for a categorized list of commands, or excelcli sheet --help (replace sheet) to view action-specific options. Always follow the session pattern: excelcli session open <file> → run commands with --session <id> → excelcli session save/close <id>. See CLI Guide for complete documentation.

Project Information

License: MIT License - see LICENSE file

Contributing: See CONTRIBUTING.md for guidelines

Built With: This entire project was developed using GitHub Copilot AI assistance

Acknowledgments:

  • Microsoft Excel Team - For comprehensive COM automation APIs
  • Model Context Protocol community - For the AI integration standard
  • Open Source Community - For inspiration and best practices

SEO & Discovery

Excel Automation • Automate Excel with AI • MCP Server • Model Context Protocol • GitHub Copilot Excel • AI Excel Assistant • Power Query Automation • Power Query M Code • Power Pivot Automation • DAX Measures • DAX Automation • Data Model Automation • PivotTable Automation • VBA Automation • Excel Tables Automation • Excel AI Integration • COM Interop • Windows Excel Automation • Excel Development Tools • Excel Productivity • Excel Scripting • Conversational Excel • Natural Language Excel