Files
sbroenne__mcp-server-excel/vscode-extension
Stefan Broenner e512204732 feat: Add comprehensive Chart operations support (Regular Charts and PivotCharts) (#230)
* feat: Add comprehensive Chart operations support (Regular Charts and PivotCharts)

Implements complete chart management functionality across all three layers:
- Core Commands: 15 methods for chart lifecycle, data source, and appearance operations
- MCP Server Tool: excel_chart with 15 actions exposed to LLM agents
- CLI Commands: chart command with 15 actions for command-line automation

Core Implementation (940+ lines):
- IChartCommands.cs: Interface defining 15 chart operations
- ChartCommands.Lifecycle.cs (500+ lines): List, Read, CreateFromRange, CreateFromPivotTable, Delete, Move
- ChartCommands.DataSource.cs (200+ lines): SetSourceRange, AddSeries, RemoveSeries
- ChartCommands.Appearance.cs (240+ lines): SetChartType, SetTitle, SetAxisTitle, ShowLegend, SetStyle
- Strategy Pattern: RegularChartStrategy and PivotChartStrategy (220+ lines each)
- ChartType.cs: 70+ chart type enum values (Column, Bar, Line, Pie, Area, Scatter, etc.)
- ChartResults.cs: 4 result classes (ChartListResult, ChartInfoResult, ChartCreateResult, ChartUpdateResult)

MCP Server Integration (473 lines):
- ExcelChartTool.cs: Main tool with 15 actions
- ChartAction enum: 15 values (List, Read, CreateFromRange, CreateFromPivotTable, Delete, Move, SetSourceRange, AddSeries, RemoveSeries, SetChartType, SetTitle, SetAxisTitle, ShowLegend, SetStyle)
- ToActionString() extension: Maps ChartAction to kebab-case strings

CLI Integration (368 lines):
- ChartCommand.cs: Command<Settings> pattern with 15 actions
- Registered in Program.cs with DI support

Testing (27 tests + smoke test):
- ChartCommandsTests.Lifecycle.cs: 9 tests covering chart creation and management
- ChartCommandsTests.Appearance.cs: 10 tests covering appearance customization
- ChartCommandsTests.DataSource.cs: 8 tests covering data source operations
- CoreCommandsCoverageTests.cs: Automated verification of enum/method coverage
- McpServerSmokeTests.cs: End-to-end smoke test for excel_chart tool (now includes Chart!)
- ToolDiscoveryTests.cs: Discovery verification for excel_chart

Features:
- Regular Charts: Static charts from Excel ranges (A1:D10)
- PivotCharts: Dynamic charts linked to PivotTables
- 70+ chart types supported (Column, Bar, Line, Pie, Area, Scatter, Bubble, Stock, Surface, Radar, etc.)
- Full positioning control (left, top, width, height in points)
- Series management (add/remove data series)
- Appearance customization (titles, axes, legends, styles)
- Round-trip validation in all tests

Architecture:
- Strategy Pattern: Separates Regular vs PivotChart logic
- Batch-aware: All operations use IExcelBatch for performance
- COM-safe: Proper resource cleanup with try/finally blocks
- Range object fix: SetSourceData requires Range object, not string

Documentation:
- specs/CHART-API-SPECIFICATION.md: 400+ line comprehensive specification
- All methods fully documented with XML comments
- Examples provided for all operation types

Builds successfully with 0 warnings, 0 errors.
All 27 Core tests pass.
Smoke test passes (validates end-to-end workflow with all 13 tools).
100% Core method coverage verified.
MCP tool discoverable and functional.

* fix: Update Chart test assertions to match Excel SERIES formula behavior

- SetSourceRange tests now check for Sheet1 + column references ($D$, $E$, $A$, $B$) instead of simple ranges
- AddSeries_InvalidSeriesIndex now expects COMException for invalid index instead of Success=false
- All 26 Chart integration tests now pass (9 lifecycle, 8 data source, 9 appearance)
- Fixes #229

* refactor: Rewrite Connection tests to accurately document Excel COM behavior

- TEXT/WEB connections: Create works successfully
- OLEDB connections: Fail with ArgumentException (Excel COM Add2() limitation)
- ODBC connections: Create succeeds even without valid DSN
- Duplicate names: Excel handles gracefully (prevents or auto-renames)
- Removed confusing 'test always passes' logic
- Added clear documentation about connection type support
- Fixed exception propagation in CreateConnection helper (removed InvalidOperationException wrapping)

All 21 Connection tests now pass (1 skipped).

* feat(connection): Add ODC import and enhance SetProperties with connection string/command text/description updates

FEATURE ENHANCEMENTS:
- Add ImportFromOdc action to import Office Data Connection (.odc) files
- Expose connectionString, commandText, description parameters in SetProperties (was behavior-only)
- Add exception handler for Excel 0x800A03EC error (ODC connection string updates blocked)
- Block TEXT/WEB connection creation via Create (redirect to Power Query)
- Add import-odc action to CLI with --odc-file parameter

IMPLEMENTATION:
- New ConnectionCommands.ImportOdc.cs with AddFromFile COM API
- Enhanced UpdateConnectionProperties to handle all 7 properties (connection string, command text, description + 4 behavior properties)
- MCP Tool: SetProperties accepts newConnectionString, newCommandText, newDescription parameters
- CLI: ExecuteImportOdc method with OdcFilePath setting
- Exception scoping: Only catches 0x800A03EC when updating connection string

TESTING (13 new tests):
- ConnectionCommandsTests.ImportOdc.cs:
  * ImportFromOdc_ValidFile_ImportsConnection
  * ImportFromOdc_MissingFile_ReturnsError
  * ImportFromOdc_DuplicateImport_AddsSecondConnection
  * ImportFromOdc_ThenUpdateCommandText_RefreshSucceeds (proves functional query change)
  * ImportFromOdc_ThenUpdateCommandText_ConnectionUpdated
  * ImportFromOdc_ThenUpdateDescription_ConnectionUpdated
  * CreateConnection_ThenUpdateConnectionString_Succeeds (proves ODBC connections allow updates)
- ConnectionCommandsTests.Create.cs:
  * Create_TextConnection_ThrowsNotSupportedException (TEXT blocked)
  * Create_WebConnection_ThrowsNotSupportedException (WEB blocked)
  * Create_OleDbConnection_ThrowsArgumentException (Excel COM limitation)
  * Create_OdbcConnection_ReturnsSuccess (ODBC works)
  * Updated Create_DuplicateName and Create_WithDescription to use ODBC
- Helper: SQLiteDatabaseHelper for reliable OLEDB testing

DOCUMENTATION:
- Updated README tool counts: 10 actions (was 9)
- Updated architecture-patterns.instructions.md: 11 tools (corrected from 12)
- Updated excel_connection tool description: ODC import, TEXT/WEB removal guidance
- Added Directory.Packages.props: Microsoft.Data.Sqlite package
- Removed outdated vscode-extension/INSTALL.md (content merged to main README)

KEY FINDINGS:
- ODC-imported connections: Connection string updates blocked (0x800A03EC)
- Programmatically-created ODBC connections: Connection string updates work
- Command text updates are functional (refresh executes new query, not cosmetic)
- TEXT/WEB connections now blocked from Create (use Power Query or ODC import)

* refactor: Remove ODC import functionality (blocked by Windows Defender ASR)

- Removed ImportFromOdc action from ConnectionAction enum and all implementations
- Deleted ConnectionCommands.ImportOdc.cs (implementation file)
- Deleted ConnectionCommandsTests.ImportOdc.cs (all test files)
- Removed import-odc from MCP tool, CLI, and interface
- Removed OdcFilePath CLI parameter
- Fixed Delete and View tests to use ODBC connections instead of TEXT
- Updated Refresh tests to use simpler ODBC connections
- Updated all READMEs: connection count 10→9 actions, 155→154 total actions

REASON:
Excel's AddFromFile() COM API creates .lnk shortcuts in 'My Data Sources' folder,
triggering Windows Defender Attack Surface Reduction (ASR) rule 'Block Office
applications from creating executable content'. This blocks all users with
default Defender policies (common in enterprise).

ALTERNATIVE APPROACH:
Users can manually create connections via excel_connection create action with
connection strings, or use Power Query (excel_powerquery) for data imports.

* feat: Enhance Excel tools with timeout safeguards and error handling

- Added timeout safeguards to `ExcelPivotTableTool` and `ExcelPowerQueryTool` to handle long-running operations, returning suggested next actions on timeout.
- Updated `CreateFromDataModel` and `LoadToPowerQueryAsync` methods to include detailed error messages and operation context in case of timeouts.
- Removed unused SQLite database helper class and replaced it with ACE OLEDB helper functions for better integration testing.
- Updated connection tests to utilize the new ACE OLEDB helper methods, ensuring proper creation and refreshing of connections.
- Adjusted README to reflect the current number of supported operations (154) in the Excel MCP Server.
2025-11-22 20:33:18 +00:00
..

Excel MCP Server - AI-Powered Excel Automation

GitHub License: MIT

Control Microsoft Excel with AI through GitHub Copilot - just ask in natural language!

Instead of clicking through Excel menus, simply ask:

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"
  • "Build a DAX measure calculating year-over-year growth with proper time intelligence"

Formatting & Styling (No Programming Required):

  • "Format revenue columns as currency, make headers bold with blue background"
  • "Apply conditional formatting to highlight values above $10,000 in red"
  • "Convert this range to an Excel Table with filters and totals row"

Workflow Automation:

  • "Find all cells containing 'Q1 2024' and replace with 'Q1 2025'"
  • "Add data validation dropdowns to Status column with options: Active, Pending, Completed"

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

Unlike third-party libraries that manipulate .xlsx files directly (risking file corruption), Excel MCP Server 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 as you work with live Excel files
  • ✅ Comprehensive automation - Currently supports 154 operations across 11 specialized tools

Quick Example:

You: "Create a Power Query named 'SalesData' that loads from data.csv into a worksheet and data model and creates matching pivot tables. Format it professionally."

Copilot uses Excel MCP Server to:
1. Create/open an Excel workbook
2. Add the Power Query with proper M code based on its analysis of the CSV file
3. Load the data to a worksheet and a data model
4. Create profesionally formatted pivot tables

Result: Just what you requested - without touching Excel once.

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

  • ❌ Linux/macOS users (Windows + Excel installation required)
  • ❌ High-volume batch operations (consider Excel-free alternatives)

Quick Start

  1. Install this extension (you just did!)
  2. Ask Copilot in the chat panel:
    • "List all Power Query queries in workbook.xlsx"
    • "Create a DAX measure for year-over-year revenue growth"
    • "Export all Powere Queires and VBA modules to .vba files for version control"

That's it! The extension automatically installs .NET 8 runtime and includes a bundled MCP server.

➡️ Learn more and see examples

Requirements

  • Windows OS - Excel COM automation requires Windows
  • Microsoft Excel 2016+ - Must be installed on your system
  • .NET 8 Runtime - Automatically installed by the extension

What's Included

Features

The Excel MCP Server provides 11 specialized tools (154 operations) for comprehensive Excel automation:

Tool Operations Purpose
excel_powerquery 9 actions Power Query M code: create, view, update, delete, load configuration, list sources
excel_datamodel 14 actions Power Pivot (Data Model): DAX measures, relationships, discover structure (tables, columns), refresh
excel_table 23 actions Excel Tables: lifecycle, columns, filters, sorts, structured references, number formatting
excel_pivottable 25 actions PivotTables: create, field management, aggregations, filters, sorting, grand totals control, extract data
excel_range 42 actions Ranges: get/set values/formulas, formatting, validation, clear, copy, insert/delete, find/replace, merge, cell protection
excel_conditionalformat 2 actions Conditional Formatting: add rules (cell value, expression-based), clear rules
excel_vba 6 actions VBA: list, view, export, import, update, run modules
excel_connection 9 actions Connections: OLEDB/ODBC management, properties, refresh
excel_worksheet 16 actions Worksheets: lifecycle, tab colors, visibility, copy/move between workbooks
excel_namedrange 7 actions Named ranges: list, get, set, create, delete, update, bulk create
excel_file 5 actions File operations: open session, close session (with save option), create empty, test
Total 154 actions

"Excel is not installed" error:

  • Ensure Microsoft Excel 2016+ is installed on your Windows machine
  • Try opening Excel manually to verify it works

"VBA access denied" error:

  • VBA operations require one-time manual setup in Excel
  • Go to: File → Options → Trust Center → Trust Center Settings → Macro Settings
  • Check "Trust access to the VBA project object model"

Copilot doesn't see Excel tools:

  • Restart VS Code after installing the extension

  • Troubleshooting

  • Check Output panel → "Excel MCP Server" for connection status

Documentation & Support

License

MIT License - see LICENSE


Built with GitHub Copilot | Powered by Model Context Protocol