117 Commits

Author SHA1 Message Date
Stefan Broenner 66196cfb68 docs: update tool/operation counts and lists to match code (#290)
Fixes #289

- Update MCP Server: 12 tools, 180 operations
- Update CLI: 13 command groups, 172 operations
- Fix gh-pages/index.md operation tables:
  - PivotTables: 25 → 30 (added calculated fields/members, grouping, layout)
  - DataModel: 15 → 16 (added delete-table)
  - File: 5 → 6 (added list)
  - Worksheets: added set-visibility
  - Removed non-existent operations from tables
- Update readme-management.instructions.md with verification guidance
- Update GitHub repo description and topics

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-12-06 14:51:33 +00:00
Stefan Broenner a4c90850b1 feat: Add list and delete operations for calculated fields and calculated members (#288)
- Add ListCalculatedFields and DeleteCalculatedField for regular PivotTables
- Add ListCalculatedMembers and DeleteCalculatedMember for OLAP PivotTables
- Add CalculatedFieldInfo and CalculatedFieldListResult model types
- Update MCP Server tool with new action handlers
- Add comprehensive test coverage (16 total tests)

Fixes #287

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-12-06 13:21:12 +00:00
Stefan Broenner b00ee54dfe perf: Optimize PivotTable RefreshTable() calls (#286)
* perf: Remove unnecessary RefreshTable() calls and optimize test fixtures

Performance optimizations:

1. Remove unnecessary RefreshTable() from visual-only operations:
   - SetFieldFormat (OLAP + Regular) - NumberFormat is visual only
   - SetSubtotals (OLAP + Regular) - removed 2 calls each
   - SetLayout (OLAP + Regular) - layout changes don't need refresh
   - SetGrandTotals (OLAP + Regular) - visual setting
   - SortField (OLAP + Regular) - sorting is visual
   - SetFieldName (Regular only) - OLAP throws exception

2. Fix SetFieldFunction measure lookup bug:
   - Added NormalizeMeasureName() helper to extract measure name from [Measures].[Name] format
   - Fixed lookup to use normalized name

3. Optimize test fixture sharing:
   - Changed from IClassFixture (1 fixture per class) to ICollectionFixture (1 fixture for ALL classes)
   - Created DataModelTestsDefinition collection for 6 test classes
   - Reduces fixture setup from ~9 min to ~1.5 min

4. Fix test measure name conflict:
   - Changed AddValueField test to use 'Regional Sales Total' instead of 'Total Sales'

Total RefreshTable() calls removed: 13
Test classes now sharing fixture: 6

* test: Add diagnostic tests for RefreshTable() behavior

Add 9 raw Excel COM API tests to empirically determine:
- Which PivotTable operations require RefreshTable()
- Which operations work immediately without RefreshTable()
- Persistence behavior with and without RefreshTable()

Key findings documented:
- Structural changes (Orientation) need RefreshTable() for persistence
- Visual properties (NumberFormat) work after structure is refreshed
- In-memory operations don't need refresh for immediate effect

* perf: Remove 2 more unnecessary RefreshTable() calls

Based on diagnostic tests proving persistence works without refresh:
- SetFieldFunction: Function changes persist without RefreshTable()
- SetFieldFilter: Filter changes persist without RefreshTable()

Added 2 new diagnostic tests:
- FunctionChange_Persistence_WithoutRefresh_VerifySaveAndReopen
- FilterChange_Persistence_WithoutRefresh_VerifySaveAndReopen

Total RefreshTable() calls removed: 15 (13 initial + 2 additional)

---------

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-12-06 12:18:36 +00:00
Stefan Broenner 1b4f9bfdcf feat: Add Docker support for Glama.ai MCP registry integration (#284)
Adds Dockerfile and supporting files to enable Glama.ai to inspect
and discover the Excel MCP server's tools.

New files:
- Dockerfile: Multi-stage build for Linux container (inspection only)
- .dockerignore: Optimize Docker build context
- glama.json: Glama registry metadata
- docs/GLAMA-DOCKER-SUPPORT.md: Documentation

Code quality improvements (removed .editorconfig suppressions):
- Remove unused TimeSpan? parameter from ExcelSession.CreateNew
- Add missing XML docs to IRangeCommands.SetValues
- Make Unload() and FindTableAndColumn() static (CA1822)
- Update test callers to use static method syntax
- Change CA1822 from suggestion to warning in .editorconfig
- Remove CS1573 suppression from .editorconfig

Fixes #283

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-12-06 07:18:39 +00:00
Stefan Broenner 0bb29be3be feat: DAX formula locale handling for European locales (#282)
* Fix #279: Power Query lifecycle cleanup for Data Model connections

BREAKING CHANGES:
- Unload now removes Data Model connections (not just worksheet tables)
- Delete now removes Data Model connections (prevents orphan connections)

IMPROVEMENTS:
- List correctly reports IsConnectionOnly for Data Model-only queries
- Update uses connection.Refresh() fallback for Data Model-only queries
  (no worksheet table to refresh)

NEW TESTS:
- PowerQueryCommandsTests.LifecycleCleanup.cs: 8 tests for Issue #279
- PowerQueryCommandsTests.UpdateErrors.cs: 3 tests for error handling
- DataModelComApiBehaviorTests.cs: 11 diagnostic scenarios
- PowerQueryComApiBehaviorTests.cs: 15 diagnostic scenarios

DOCUMENTATION:
- docs/COM-API-BEHAVIOR-FINDINGS.md: Empirical COM API behavior findings
- excel_powerquery.md: Updated prompt docs for Data Model cleanup

DELETED:
- PowerQueryCommandsTests.ErrorQueries.cs: Referenced non-existent local file

All 53 PowerQuery and DataModel tests pass.

* fix: Use locale-aware format translation instead of global Excel settings

- Renamed DateFormatTranslator to NumberFormatTranslator
- Extended translator to handle decimal/thousands separators (. and ,)
- Removed global UseSystemSeparators/DecimalSeparator/ThousandsSeparator
  settings from ExcelSession and ExcelBatch (these modified Excel app defaults)
- Added IsEnglishNumberLocale property to detect US-style number separators
- Format codes are now translated at point of use, not by changing app defaults
- Updated all references from DateFormatter to FormatTranslator
- Removed unused WithUSFormatSeparators helper from RangeCommands

This approach translates US format codes (like $#,##0.00) to locale-specific
codes (like $#.##0,00 on German Excel) without modifying Excel's global settings.
Previous approach of changing Application.DecimalSeparator affected all
workbooks in the Excel instance, which is not desirable.

* feat: DAX formula locale handling for European locales (#281)

- Add DaxFormulaTranslator to convert US comma separators to semicolons on European locales
- Integrate translator in CreateMeasure and UpdateMeasure operations
- Power Pivot uses system culture (CultureInfo.CurrentCulture), not Excel International settings
- Preserve commas inside string literals and column references
- Add 5 integration tests for DAX locale translation
2025-12-05 13:55:49 +00:00
Stefan Broenner 827704e63e feat(datamodel): add read-relationship action for viewing individual relationships (#278)
Adds the read-relationship action to excel_datamodel tool, completing
full CRUD coverage for relationships in the Data Model.

Changes:
- Add DataModelRelationshipViewResult result type
- Add ReadRelationship method to IDataModelCommands interface
- Implement ReadRelationship in DataModelCommands.Read.cs
- Add ReadRelationship enum value to DataModelAction
- Add action string mapping for read-relationship
- Add ReadRelationshipAsync handler in ExcelDataModelTool

Documentation:
- Update FEATURES.md with 15 Data Model operations (was 14)
- Update all READMEs with 173 total operations (was 172)
- Update gh-pages/index.md with new action in reference table
- Document hidden columns/relationships/measures API limitation

Closes #277
2025-12-05 07:19:10 +00:00
Stefan Broenner b6bcd97219 feat: Replace session-based cross-workbook operations with atomic file operations (#274)
- Replace copy-to-workbook and move-to-workbook with copy-to-file and move-to-file
- Remove unused targetSessionId parameter from worksheet tool
- Fix sheet positioning bug when copying with beforeSheet/afterSheet
- Add excel_worksheet.md prompt file for LLM cross-file operation guidance
- Add ExcelWorksheetPrompts.cs to register the prompt
- Update all documentation and comments to reflect new operation names

Closes #273
2025-12-04 18:07:34 +00:00
Stefan Broenner abfea2859d fix: GetLoadConfig incorrectly detects LoadToBoth as LoadToTable (#271) (#272)
- Simplified GetLoadConfig to use WorkbookConnection.InModel property
- Removed legacy fallback logic (DataModel_ markers, Named Range markers)
- Added 8 comprehensive tests for all PowerQueryLoadMode values
- All tests pass (ConnectionOnly, LoadToTable, LoadToDataModel, LoadToBoth)
2025-12-04 16:44:36 +00:00
Stefan Broenner c8eb20349d Fix CreateFromPivotTable for OLAP/Data Model PivotTables (#268)
* Fix CreateFromPivotTable for OLAP/Data Model PivotTables

Fixes #267

The PivotCache.CreatePivotChart() method has unreliable COM parameter
binding with dynamic types, throwing DISP_E_UNKNOWNNAME for OLAP sources.

Solution: Use unified Shapes.AddChart() + Chart.SetSourceData() approach
that works for all PivotTable types (range-based, table-based, and OLAP).

Changes:
- ChartCommands.Lifecycle.cs: Unified implementation for all PivotTables
- ChartCommandsTests.Lifecycle.cs: Added 3 tests for regular PivotTables
- ChartCommandsTests.OlapPivotChart.cs: New file with 6 OLAP-specific tests

All 35 Chart feature tests pass.

* fix: update CHANGELOG for OLAP PivotChart Creation support in CreateFromPivotTable
2025-12-04 09:35:10 +00:00
Stefan Broenner 3fae0b51ac fix: locale-independent number and date format handling (#264)
Fixes #263

- Force US separators (UseSystemSeparators=false) at Excel instance creation
- Add DateFormatTranslator to translate US date codes (d/m/y) to locale codes
- Fix OlapPivotTableFieldStrategy.SetFieldFormat for pre-existing measures
- Update LLM documentation to guide use of US format codes
- Add 6 date translation tests + 2 PivotTable format tests
2025-12-04 07:02:00 +00:00
Stefan Broenner b48d12cdf0 fix: OLAP PivotTable AddValueField disambiguation and AddDataField fix (#261) (#262)
* fix: use AddDataField() instead of Orientation for OLAP measures

Fixes #261

The previous approach of setting cubeField.Orientation = xlDataField
could fail with E_INVALIDARG (0x80070057) for CubeFields in certain
states (e.g., long-lived workbooks, complex Data Model configurations).

Using pivot.AddDataField(cubeField) is more robust and works consistently
for all CubeFieldTypes.

Changes:
- MODE 1 (pre-existing measure): Use AddDataField() at line 360
- MODE 2 (auto-create measure): Use AddDataField() at line 474
- Added comments explaining why this approach is preferred

* fix: OLAP PivotTable measure disambiguation uses exact matching only

BREAKING: Removed Contains() partial matching that caused [Measures].[ACR]
to incorrectly match table columns like [ACR Types].[ACRTypeKey].

Fixes:
- Issue 1: AddValueField now uses cubeFields.Item(fieldName) for exact match
- Issue 2: ListFields correctly reports field area after AddValueField
- Issue 3: Response confirmation now shows correct field added

Changes:
- OlapPivotTableFieldStrategy.cs: GetCubeFieldByName uses exact matching only
- PivotTableCommands.cs: GetFieldByName uses same exact matching pattern
- Consolidated DataModelTestsFixture + PivotTableRealisticFixture into
  unified DataModelPivotTableFixture with disambiguation test data
- Added 4 new disambiguation tests validating exact matching behavior

Test coverage: 20 tests pass (4 disambiguation + 4 DataModel PivotTable +
12 DataModel commands)
2025-12-03 18:49:04 +00:00
Stefan Broenner 299ee68703 feat: Locale-aware number formatting & LLM guidance improvements (#260)
* feat(range): Add locale-aware number formatting with separate actions

PROBLEM:
- Format codes like '\$#,##0.00' interpreted incorrectly on non-US locales
- German Excel treated '.' as thousands separator, ',' as decimal
- LLM API had confusing design with 'formatCode OR numberFormatCategory'

SOLUTION:
1. Use NumberFormatLocal instead of NumberFormat (interprets locale correctly)
2. Use LocaleAwareFormatBuilder to generate format codes using CultureInfo
3. Separate into two clean actions for better LLM usability:
   - SetNumberFormat: Structured params only (numberFormatCategory required)
   - SetNumberFormatCustom: Raw formatCode only (expert use)

NEW FILES:
- NumberFormatOptions.cs: Enums and LocaleAwareFormatBuilder

MODIFIED:
- RangeCommands.NumberFormat.cs: NumberFormatLocal + SetNumberFormatStructured
- ExcelRangeTool.cs: Two separate actions, cleaner parameter routing
- ToolActions.cs: SetNumberFormatCustom enum added
- ActionExtensions.cs: set-number-format-custom mapping
- audit-core-coverage.ps1: Added SetNumberFormatCustom to known exceptions
- check-mcp-core-implementations.ps1: Added SetNumberFormatCustom to known exceptions

VERIFIED:
- German locale shows correct formats: EUR#.##0,00, 0,0%, #.##0,00
- Build passes with 0 warnings
- All pre-commit checks pass

* docs(range): Add LLM guidance for number formatting actions

- Add [Description] attribute to excel_range tool with number formatting guidance
- Create excel_range.md prompt with detailed action comparison
- Create ExcelRangePrompts.cs to expose prompt via MCP

Guidance helps LLMs choose between:
- SetNumberFormat: RECOMMENDED, locale-aware, structured parameters
- SetNumberFormatCustom: Expert use, raw format codes, locale-sensitive

* docs: Update instructions to use XML documentation instead of [Description]

MCP SDK now extracts tool descriptions from XML documentation
(/// <summary>) rather than [Description] attributes.

Updated files:
- mcp-server-guide.instructions.md: XML docs guidance and examples
- critical-rules.instructions.md: Rule 18 now shows XML doc patterns
- bug-fixing-checklist.instructions.md: Reference XML docs not [Description]
- ExcelRangeTool.cs: Move description to XML docs, remove [Description]

* docs: Add guidance to ask user before closing when showExcel=true

When Excel is visible (showExcel=true), the user is actively watching.
LLM should ask before closing instead of auto-closing, since user may want
to inspect results, make manual changes, or continue working.

Updated files:
- Program.cs: Server instructions with new 'ASK BEFORE CLOSING' section
- ExcelFileTool.cs: XML docs with same guidance

* feat: Add operation tracking to prevent premature session close

- Add BeginOperation/EndOperation tracking in SessionManager
- Block Close action when operations are still running
- Add ValidateClose method with CloseValidationResult record
- Enhanced List action to return activeOperations, canClose, isExcelVisible
- Add force parameter to CloseSession for emergency override
- Track showExcel flag per session for visibility status
- Updated server instructions about automatic operation tracking
- Fixed missing FileAction.List mapping in ActionExtensions

Tests:
- 18 new unit tests for SessionManager operation tracking
- 4 new MCP integration tests for ExcelFileTool operation tracking

This prevents data loss from closing sessions while parallel operations
are still running. The server now automatically tracks operations and
returns a blocking error with activeOperations count if close is attempted
while operations are in progress.

* feat(datamodel): add DeleteTable action to remove orphaned Data Model tables

- Add DeleteTable to DataModelAction enum and ToActionString mapping
- Add DeleteTable method to IDataModelCommands interface
- Implement DeleteTable using SourceWorkbookConnection.Delete() pattern
  (ModelTable is read-only, must delete via associated connection)
- Add DeleteTable handler in ExcelDataModelTool
- Add 3 integration tests covering success and error scenarios

This allows cleanup of orphaned tables when Power Query is deleted
and recreated with loadDestination: data-model.

* fix(connection): correct error message for Power Query connection deletion

Changed error message from outdated 'pq-delete' to correct
'excel_powerquery with action Delete' when user attempts to
delete a Power Query connection via excel_connection tool.

* Simplify number formatting: auto-LCID for date/time, streamlined docs

- Add EnsureDateTimeLcid() to automatically prefix date/time formats with [$-409]
- LLMs no longer need to know about LCID - just use 'mm/dd/yyyy' directly
- Currency symbols ($, €, £, ¥) are literal - no special handling needed
- Simplified excel_range.md from 95 lines to 28 lines (one table, essentials only)

* Simplify telemetry: remove redundant TrackPageView

- Remove TrackPageView call (Usage blades don't work for console apps)
- Keep TrackEvent for tool usage analytics (customEvents table)
- Keep TrackRequest for performance metrics (Performance blade)
- Update documentation to reflect simplified telemetry model

* Track unhandled exceptions and file context in telemetry

- Add try-catch in Program.Main() to track MCP SDK/transport errors
- Pass excelPath to TrackToolInvocation for file-level analytics grouping
- Ensures telemetry is flushed before exit on unhandled exceptions

* docs: fix showExcel default guidance and incorrect action names

- Fix ServerInstructions to clarify showExcel:false is DEFAULT (not showExcel:true)
- Update tool description to emphasize default is hidden/faster mode
- Fix incorrect pivottable actions: 'create' with sourceType -> 'create-from-table'/'create-from-datamodel'
- Remove non-existent 'create-bulk' action reference from namedrange examples
- Fix NamedRangeCommands comment to match actual exposed operations
- Update VS Code extension copilot-instructions with correct defaults and actions

* docs: enhance copilot instructions for Excel MCP usage clarity

* Merge origin/main: keep operation tracking features from this branch

* fix: address GitHub Advanced Security warnings

- Fix constant condition in ConnectionCommands (check HasValue before switch)
- Add using statement for SessionManager in Dispose_CleansUpAllTracking test
- Suppress CA3003 (Path.Combine) in test code - controlled inputs
- Suppress CA1031 (generic catch) in test cleanup - best effort disposal
- Use .Where() instead of if-in-foreach for filtering
2025-12-03 12:26:39 +00:00
Stefan Broenner b6e8899c12 docs: add List action documentation to excel_file tool (#258)
Improve tool documentation to highlight the List action for session verification:
- Add SESSION VERIFICATION section at top of tool documentation
- Document that List returns active sessions without Excel COM calls
- Add workflow example: list -> check sessionId exists
- Clarify List is the lightweight way to verify session existence
- Add List to known exceptions in both audit scripts (MCP-specific action)

This helps LLMs discover the proper way to verify sessions instead of
using heavier operations like excel_chart or excel_worksheet List actions.
2025-12-01 20:14:25 +00:00
Stefan Broenner 34b90e8349 fix: MCP Registry publishing - shorten description and fix README detection (#256)
- Shorten server.json description from 184 to 95 characters (MCP Registry limit is 100)
- Fix workflow to decode Invoke-WebRequest byte array as UTF-8 string before regex matching

Fixes #255
2025-12-01 19:40:49 +00:00
Stefan Broenner 2eec36317f fix: add [DefaultValue] attributes to MCP tool parameters for SDK 0.4.1 compatibility (#254)
MCP SDK 0.4.1-preview.1 uses AIFunctionFactory which treats ALL parameters
as required unless they have a [DefaultValue] attribute. Partial methods
cannot have C# default parameter values, so [DefaultValue] from
System.ComponentModel is required.

Changes:
- Add [DefaultValue(null)] to all nullable parameters across 12 tool files
- Add [DefaultValue(false/true)] to bool parameters as appropriate
- Fix pre-commit.ps1 smoke test filter (was SmokeTest_AllTools_LlmWorkflow,
  now SmokeTest_AllTools_E2EWorkflow)
- Add validation to pre-commit.ps1 to detect when no tests actually run
  (dotnet test returns exit code 0 even with zero matching tests)
2025-12-01 19:29:23 +00:00
Stefan Broenner 762ffd3c34 fix: MCP Registry publishing - update version regex and metadata (#253)
- Fix regex to find 'packages' instead of 'title' after version field
- Update server.json title/description to match .csproj metadata
- Fix MCP Registry API URLs to use /v0.1/servers/ path

Fixes #252
2025-12-01 18:53:33 +00:00
Stefan Broenner bf0cd4f37d fix: release workflow YAML syntax and step ordering (#249)
* fix: correct YAML syntax for release notes markdown

- Replace PowerShell here-string with string concatenation
- Use single-quoted strings for markdown code block fences
- Fixes workflow failure from invalid YAML parsing

* docs: add Rule 23 - never dismiss IDE/linter warnings as false positives

Added after incorrectly dismissing VS Code YAML errors that led to
a broken GitHub Actions workflow. Rule now requires:
- Trust tooling warnings by default
- Verify with testing or documentation before dismissing
- Use simpler approaches when uncertain

* fix: move MCP Registry publishing to end of workflow
2025-12-01 18:11:29 +00:00
Stefan Broenner 8fbd6f43fc Fix/nuget-mcpserver-package-type (#248)
* fix: add McpServer package type for NuGet and MCP Registry

.NET 8 SDK unconditionally overwrites PackageType to DotnetTool when
PackAsTool=true (Microsoft.NET.Sdk.Common.targets line ~47).

This workaround adds a custom MSBuild target that runs before GenerateNuspec
to append McpServer to the PackageType property after the SDK sets it.

Fixes:
- NuGet package now appears in MCP Server package type filter
- MCP Registry should now properly detect and update version

Verified: Generated nuspec contains both DotnetTool and McpServer types.

* fix: update package descriptions and dependencies for improved clarity and compatibility
2025-12-01 17:18:12 +00:00
Stefan Broenner d72d8f8d1b Fix/remove-telemetry-diagnostics (#247)
* chore: remove telemetry diagnostic output

* chore: update packages to .NET 10 and MCP SDK 0.4.1-preview.1

- Microsoft.Extensions.Hosting: 9.0.10 -> 10.0.0
- Microsoft.Extensions.Logging: 9.0.10 -> 10.0.0
- Microsoft.Extensions.Configuration: 9.0.10 -> 10.0.0
- Microsoft.Extensions.DependencyInjection: 9.0.10 -> 10.0.0
- System.Text.Json: 9.0.10 -> 10.0.0
- ModelContextProtocol: 0.4.0-preview.3 -> 0.4.1-preview.1

All packages forward-compatible with .NET 8.0 runtime.
No breaking changes - verified build passes with 0 warnings.

* refactor: migrate MCP tools from [Description] attributes to XML documentation

- Convert all 12 tool files to use XML docs (/// <summary>, /// <param>)
- XML docs processed by MCP SDK's XmlToDescriptionGenerator source generator
- Remove all CA1861 pragma warnings and [SuppressMessage] attributes (not needed)
- Remove dead code: ThrowUnknownAction() and invalid action error handlers
- Add GlobalUsings.cs for Chart and Range namespaces
- Update mcp-server-guide.instructions.md with NO EMOJIS rule

The XmlToDescriptionGenerator converts XML comments to [Description] attributes
at compile time, providing better IDE support and documentation integration.

* feat(mcp): add tool categories and remove outdated LLM guidance

- Add [McpMeta("category", "...")] to all 12 tools for better LLM discovery
- Remove unhelpful LLM guidance (suggestedNextActions, retryGuidance, workflowHint, operationContext)
- Update ExcelResourceProvider to use excel_file sessions

Follows principle: state facts, not guidance - LLMs figure out next steps

* fix: add prominent warning to prevent premature session close

- Update ServerInstructions in Program.cs to explicitly warn LLMs:
  - WAIT for ALL pending tool calls before closing
  - Closing while operations running causes failures
- Expand excel_file tool description with detailed session lifecycle
- Addresses race condition where close was called during parallel operations

* feat: add showExcel parameter to watch Excel during automation

- Add showExcel parameter to excel_file open action
- When true, Excel window becomes visible during operations
- Perfect for debugging, demos, and learning what AI is doing

Implementation:
- ExcelFileTool: Added showExcel parameter to ExcelFile() and OpenSessionAsync()
- SessionManager: Added showExcel parameter to CreateSession()
- ExcelSession: Added BeginBatch overload with showExcel parameter
- ExcelBatch: Sets Excel.Visible based on showExcel flag

Server instructions:
- Added prominent session close warnings (wait for all operations)
- LLM instructed to proactively offer showExcel for complex tasks
- Example prompt: 'Would you like me to show Excel so you can watch?'

Documentation updated:
- README.md: User-facing section with natural language examples
- FEATURES.md: Added to File Operations section
- INSTALLATION.md: Added tip after test installation step
- gh-pages/index.md: Added tip to Interactive Development feature
- McpServer README: Added to AI-Powered Workflows list
- VS Code extension copilot-instructions.md: LLM guidance
2025-12-01 16:37:29 +00:00
Stefan Broenner 073f25450b refactor: simplify telemetry - always enabled, build-time connection string (#246)
* refactor: simplify telemetry - always enabled, build-time connection string

- Remove opt-out functionality (EXCELMCP_TELEMETRY_OPTOUT)
- Embed AppInsights connection string at build time via MSBuild
- Add Directory.Build.props.user for local dev connection string
- Remove runtime environment variable lookup for connection string
- Update release workflows to pass connection string to build
- Remove obsolete test.runsettings file
- Simplify IsEnabled to always return true

* refactor: consolidate prompts and improve tool descriptions

- Reduce prompts from 14 to 2 (keep only high-value guides)
- Remove 13 orphaned .md content files
- Fix ExcelWorksheetTool incorrect 'save' action reference
- Improve ExcelRangeTool and ExcelNamedRangeTool descriptions
- Slim ServerInstructions to essential info only
- Remove redundant telemetry flush (SDK handles automatically)

* refactor(telemetry): disable dependency tracking for HTTP calls in telemetry configuration

* test hook

* fix: correct Application Insights telemetry context

- Set Component.Version explicitly to override SDK auto-detection
  (was picking up Excel COM interop 15.0.0.0 instead of app 1.0.0)
- Anonymize cloud_RoleInstance (was exposing machine name)
- Now all telemetry context values are privacy-safe:
  - application_Version: from assembly metadata
  - cloud_RoleName: fixed 'ExcelMcp.McpServer'
  - cloud_RoleInstance: anonymous hash 'instance-xxxx'
  - user_Id: anonymous hash of machine identity
  - session_Id: random per session

* fix: telemetry improvements for Users/Sessions analytics

- Remove debug mode from telemetry (simplify code)
- Fix PageView tracking to include duration (required for User Flows)
- Always override application_Version (SDK picks up Excel 15.0.0.0)
- Add explicit Flush() call in smoke tests for reliable telemetry delivery
- Fix smoke test shutdown to use graceful shutdown before cancellation

Telemetry now correctly populates:
- requests table (with duration, success, resultCode)
- pageViews table (with duration for User Flows)
- user_Id and session_Id (for Users/Sessions blades)
- application_Version (MCP Server version, not Excel)
2025-12-01 13:34:39 +00:00
Stefan Broenner 403ecfaf73 fix: replace empty catch blocks with specific exception types (#244)
* fix: replace empty catch blocks with specific exception types (#213)

- NamedRangeCommands.Operations.cs: Replace empty catch blocks with
  COMException handlers for COM interop resilience
- PowerQueryCommands.Lifecycle.cs: Replace generic Exception catch with
  COMException for accurate error handling
- ExcelComSmokeTests.cs: Replace empty catches with InvalidOperationException
  and Win32Exception handlers for process cleanup

Addresses CodeQL alerts: cs/empty-catch-block, cs/catch-of-all-exceptions

Fixes #213

* fix: replace additional empty catch blocks with specific exception types

- VbaCommands.cs: Replace empty catch and generic catch with SecurityException
  for registry access operations
- PowerQueryCommands.Lifecycle.cs: Replace empty catch with COMException for
  CommandText property access
- PivotTableCommands.Lifecycle.cs: Replace empty catches with COMException for
  field count access (RowFields, ColumnFields, DataFields, PageFields)
- DataModelCommands.Read.cs: Replace empty catches with COMException and
  RuntimeBinderException for FormatInformation/FormatString access

All catches now have specific exception types and explanatory comments.

* chore: configure CodeQL suppressions for intentional patterns

Suppress CodeQL alerts for legitimate exception handling patterns:

- MCP Tools: catch(Exception) required for JSON error responses (MCP protocol)
- CLI Commands: catch(Exception) for user-friendly error messages
- COM Interop: exception handling at session boundaries for cleanup
- Dynamic COM: late binding is standard pattern for Excel automation
- GC.Collect: required for COM object cleanup per Microsoft guidance
- Test paths: Path.Combine safe in isolated test directories
- Generated code: Regex generator output triggers false positives

These patterns are intentional by design, not bugs to fix.
2025-11-26 08:29:49 +00:00
Stefan Broenner f44c23e478 feat(telemetry): Switch to Application Insights SDK for full Usage analytics (#243)
Replace OpenTelemetry with Application Insights SDK to enable Users, Sessions, Funnels, and User Flows analytics in Azure portal.

Changes:

- Remove OpenTelemetry packages

- Use Microsoft.ApplicationInsights SDK directly (v2.23.0)

- Add ExcelMcpTelemetryInitializer for User.Id/Session.Id context

- Simplify ExcelMcpTelemetry to use TelemetryClient.TrackEvent()

- Convert to static SensitiveDataRedactor

- Update .NET SDK to 8.0.416

Fixes #239
2025-11-26 06:48:30 +00:00
Stefan Broenner d7a2d3d24b feat: Add Application Insights telemetry via OpenTelemetry (#240)
- Add OpenTelemetry + Azure Monitor for usage tracking and unhandled exceptions
- Implement SensitiveDataRedactingProcessor to protect file paths/connection strings
- Add telemetry to all 12 MCP tools via ExecuteToolAction pattern
- Support opt-out via EXCELMCP_TELEMETRY_OPTOUT environment variable
- Add debug mode via EXCELMCP_DEBUG_TELEMETRY for local testing (console output)
- Build-time connection string injection in release workflow
- Add Bicep templates for Azure Application Insights deployment
- Add 29 tests (28 unit + 1 integration) for telemetry components
- Update developer docs with telemetry setup instructions

Closes #239
2025-11-25 06:49:02 +00:00
Stefan Broenner d2fcc5f527 Fix Rule 1b violation in PowerQuery List() (#238)
* Fix Rule 1b violation in PowerQuery List() outer catch block

- Remove catch block creating fake 'Error Query' entries
- Replace with continue statement to skip problematic queries
- Prevents exception suppression (Rule 1b compliance)
- Allows fault-tolerant listing: one bad query doesn't break entire list
- All 16 PowerQuery tests pass

* Remove inefficient try-catch in PowerQuery Refresh()

- Remove inner try-catch that suppressed COMException
- Let exceptions propagate naturally (Rule 1b)
- Remove complex fallback logic checking Success flag
- Simpler, more efficient: just throw on error
- All 16 PowerQuery tests pass

* Enforce sequential test execution and remove obsolete test

- Add xunit.runner.json to all test projects (Core, CLI, McpServer)
- Configure parallelizeAssembly: false, maxParallelThreads: 1
- Remove obsolete VbaCommandsTests.Trust.TrustScope.cs (skipped test)
- Ensures stable test execution for Excel COM interop
2025-11-24 19:47:12 +00:00
Stefan Broenner 2828175d8c Fix PowerQuery List() returning 'Error Query' for workbooks with manual tables (#237)
Fixes #236

Problem:
- List() returned fake 'Error Query' entries when workbooks contained
  manually created Excel tables (ListObjects without QueryTables)
- Accessing listObject.QueryTable on manual tables throws 0x800A03EC
- Outer catch block suppressed exceptions and created fake entries

Solution:
- Add specific try-catch for QueryTable access that continues on 0x800A03EC
- Manual tables are now skipped gracefully during IsConnectionOnly detection
- Queries return with correct names and formulas

Changes:
- PowerQueryCommands.Lifecycle.cs: Handle 0x800A03EC for QueryTable access
- Tests: Add regression test with user file + synthetic test
- Tests: Add diagnostic test to pinpoint exception location

Test results:
- All 16 PowerQuery tests pass
- New regression tests verify fix works
2025-11-24 17:39:54 +00:00
Stefan Broenner 0b6003ec09 docs: align all READMEs to MCP-first messaging, add centralized FEATURES.md (#235)
feat(table): add get-data action (CLI + MCP) with visible-only filtering
tests(tables): add GetData coverage (unfiltered + filtered)
chore: update readme-management instruction counts to 12 tools / 172 operations
2025-11-24 08:27:23 +00:00
Stefan Broenner 6b3a557870 refactor: Migrate entire codebase to exception-based pattern (void mutations, no OperationResult suppression) (#233)
* Refactor MCP tools to share error handling

* Refactor Core Commands to remove exception suppression

Per CRITICAL-RULES.md Rule 1b:
- Removed catch blocks that suppress exceptions by returning OperationResult { Success = false }
- Let exceptions propagate naturally through batch.Execute()
- Kept finally blocks for COM resource cleanup
- Removed orphaned try blocks from methods with no COM cleanup needs

Modified files:
- RangeCommands.AutoFit.cs (2 methods)
- RangeCommands.Advanced.cs (5 methods)
- RangeCommands.Validation.cs (3 methods)
- RangeCommands.Formatting.cs (3 methods)
- PivotTableCommands.GrandTotals.cs (1 method)
- OlapPivotTableFieldStrategy.cs (2 methods)
- RegularPivotTableFieldStrategy.cs (1 method)

Architecture: batch.Execute() ALREADY captures exceptions via TaskCompletionSource.
Inner try-catch suppresses exceptions and loses stack context.
Exception propagation now happens at correct layer (batch, not method).

* Update copilot-instructions: Add surgical testing guidance and exception propagation pattern

CRITICAL additions:
- Integration tests take 45+ MINUTES for full suite
- ALWAYS use surgical testing with Feature filters (2-5 min per feature)
- Core Commands NEVER wrap batch.Execute() in catch blocks
- Let exceptions propagate naturally - batch.Execute() handles via TaskCompletionSource
- ONLY use finally blocks for COM cleanup, NO catch blocks returning OperationResult

This prevents 45+ minute test runs and documents correct exception handling pattern per CRITICAL-RULES.md Rule 1b.

* Remove additional violating catch blocks from PivotTable commands

Found and removed 7 more catch blocks that violated Rule 1b:
- PivotTableCommands.Subtotals.SetSubtotals
- PivotTableCommands.Grouping.GroupByDate
- PivotTableCommands.Grouping.GroupByNumeric
- PivotTableCommands.CalculatedFields.CreateCalculatedField
- PivotTableCommands.Analysis.GetData
- PivotTableCommands.Analysis.SetFieldFilter
- PivotTableCommands.Analysis.SortField

All were inside batch.Execute() and returning OperationResult { Success = false }.
Removed catch blocks, kept finally blocks for COM cleanup.
Exceptions now propagate naturally through batch.Execute().

* refactor(core): remove violating catch block from TableCommands.DataModel.cs

Removed catch block that violated Rule 1b (CRITICAL-RULES.md).
AddToDataModel now lets exceptions propagate through batch.Execute().

Pattern removed:
catch (Exception ex) {
    return new OperationResult { Success = false, ErrorMessage = ... };
}

Rationale:
- batch.Execute() captures exceptions via TaskCompletionSource
- Inner catch suppresses exceptions and loses stack context
- Exceptions should originate from batch layer, not method layer

Part of comprehensive audit removing all violating catch blocks from Core Commands.

* test(core): fix Range style tests to expect exceptions after architectural changes

Updated 2 tests to expect exceptions instead of OperationResult { Success = false }:
- SetStyle_InvalidStyleName_ThrowsException (was ReturnsError)
- GetStyle_InvalidRange_ThrowsException (was ReturnsError)

Why Changed:
After removing violating catch blocks (Rule 1b), SetStyle() and GetStyle()
no longer catch Excel COM exceptions. batch.Execute() captures exceptions via
TaskCompletionSource and re-throws them.

Pattern:
Methods WITHOUT pre-validation → Excel COM throws → batch.Execute() captures →
Exception propagates to caller → Test must expect exception

Verified Clean:
- Tests with pre-validation (Sheet.Move, NamedRange.CreateBulk) still expect
  Success=false correctly
- Tests with business rules (OLAP calculated fields) correctly expect Success=false
- Only methods letting Excel COM throw directly needed test updates

All 2 tests now pass with architectural fix in place.

* refactor: remove async wrappers and bulk operations

Remove ViewAsync, CreateBulk methods and update documentation

* refactor(chart): Convert Chart commands to exception-based pattern

- IChartCommands: Convert 14 method signatures (OperationResult/ChartSeriesResult/ChartListResult → void/SeriesInfo/List<ChartInfo>)
- IChartStrategy: Convert 3 data operation signatures (SetSourceRange→void, AddSeries→SeriesInfo, RemoveSeries→void)
- RegularChartStrategy: Remove OperationResult wrappers, return data types directly
- PivotChartStrategy: Convert error returns to throw NotSupportedException with helpful messages
- ChartCommands implementations: Update DataSource/Lifecycle/Appearance to match new signatures
- Remove unnecessary Models using directives

CRUD ops return void (throw on error), Query ops return data types, Exceptions replace Success/ErrorMessage wrappers.
Pattern validated: Core commands build successfully with 0 errors/warnings.

* fix(chart): Fix COM cleanup in PivotChartStrategy to use finally blocks

- SetSourceRange: Move COM Release to finally block ensuring cleanup even if exception occurs
- AddSeries: Move COM Release to finally block ensuring cleanup even if exception occurs
- RemoveSeries: Move COM Release to finally block ensuring cleanup even if exception occurs
- Declare COM objects as nullable dynamic? variables before try-catch-finally

Prevents COM object leaks when exceptions occur during PivotTable name retrieval.
Finally blocks guarantee cleanup happens regardless of try/catch outcome.
Follows proper COM interop resource management pattern from excel-com-interop.instructions.md.

* refactor(chart): Remove empty catch blocks from PivotChartStrategy

- GetInfo: Remove empty catch blocks, keep only try-finally for COM cleanup
- GetDetailedInfo: Remove empty catch block, keep only try-finally for COM cleanup

Empty catch blocks are unnecessary when finally blocks handle cleanup.
Finally blocks execute regardless of exception occurrence.
Cleaner code pattern: try { operations } finally { cleanup }

* refactor(chart): Fix COM cleanup in RegularChartStrategy

- GetInfo: Move seriesCollection to try-finally without empty catch
- GetDetailedInfo: Move seriesCollection to try-finally, keep only justified catch blocks for optional properties
- Remove COM Release from try block, move to finally block
- Keep catch blocks only where fallback values make sense (HasLegend=false, etc.)

Ensures COM objects always released even if exceptions occur.
Empty catch blocks removed where no fallback action needed.

* refactor(chart): Simplify PivotChartStrategy exception messages

- SetSourceRange: Remove COM object lookup, just throw NotSupportedException
- AddSeries: Remove COM object lookup, just throw NotSupportedException
- RemoveSeries: Remove COM object lookup, just throw NotSupportedException

LLM already knows context - no need for complex COM operations to get PivotTable name.
Simpler, cleaner, no COM cleanup needed for error-only code paths.

* refactor(chart): Convert CLI ChartCommand to exception-based pattern

- Removed Result wrapper pattern from all Execute methods
- Added try-catch exception handling with proper exit codes (0=success, 1=error)
- Query operations: return data via WriteJson
- CRUD operations: void with WriteInfo success messages
- Removed WriteResult helper method (no longer needed)
- Removed unused Models using statement
- All 14 Execute methods converted:
  * ExecuteList (List<ChartInfo>)
  * ExecuteRead (ChartInfoResult)
  * ExecuteCreateFromRange (ChartCreateResult)
  * ExecuteCreateFromPivotTable (ChartCreateResult)
  * ExecuteDelete (void)
  * ExecuteMove (void)
  * ExecuteSetSourceRange (void)
  * ExecuteAddSeries (SeriesInfo)
  * ExecuteRemoveSeries (void)
  * ExecuteSetChartType (void)
  * ExecuteSetTitle (void)
  * ExecuteSetAxisTitle (void)
  * ExecuteShowLegend (void)
  * ExecuteSetStyle (void)

Part of Phase 2.2: Chart CLI Updates

* refactor(chart): Convert MCP ExcelChartTool to exception-based pattern

- Removed Result wrapper anonymous object serialization
- Query operations: serialize data types directly (List<ChartInfo>, ChartInfoResult, ChartCreateResult, SeriesInfo)
- CRUD operations (void): return success message JSON after completion
- Exception handling: ExecuteToolAction wrapper catches and serializes exceptions
- All 14 actions converted:
  * List → serialize List<ChartInfo>
  * Read → serialize ChartInfoResult
  * CreateFromRange → serialize ChartCreateResult
  * CreateFromPivotTable → serialize ChartCreateResult
  * Delete → success message JSON
  * Move → success message JSON
  * SetSourceRange → success message JSON
  * AddSeries → serialize SeriesInfo
  * RemoveSeries → success message JSON
  * SetChartType → success message JSON
  * SetTitle → success message JSON
  * SetAxisTitle → success message JSON
  * ShowLegend → success message JSON
  * SetStyle → success message JSON

Part of Phase 2.3: Chart MCP Tool Updates

* refactor(chart): Convert MCP ExcelChartTool to exception-based pattern

- Removed Result wrapper anonymous object serialization
- Query operations: serialize data types directly (List<ChartInfo>, ChartInfoResult, ChartCreateResult, SeriesInfo)
- CRUD operations (void): return success message JSON after completion
- Exception handling: ExecuteToolAction wrapper catches and serializes exceptions
- All 14 actions converted:
  * List → serialize List<ChartInfo>
  * Read → serialize ChartInfoResult
  * CreateFromRange → serialize ChartCreateResult
  * CreateFromPivotTable → serialize ChartCreateResult
  * Delete → success message JSON
  * Move → success message JSON
  * SetSourceRange → success message JSON
  * AddSeries → serialize SeriesInfo
  * RemoveSeries → success message JSON
  * SetChartType → success message JSON
  * SetTitle → success message JSON
  * SetAxisTitle → success message JSON
  * ShowLegend → success message JSON
  * SetStyle → success message JSON

Part of Phase 2.3: Chart MCP Tool Updates

* refactor(namedrange): Convert NamedRange commands to exception pattern (all layers)

Core Changes:
- INamedRangeCommands: List returns List<NamedRangeInfo>, Read returns NamedRangeValue, CRUD operations void
- Added NamedRangeValue class (POCO for Read operation)
- All methods throw exceptions on error (InvalidOperationException, ArgumentException)
- Parameter validation enforced (255 char limit, no duplicates)

CLI Changes:
- All Execute methods use try-catch with exit codes (0=success, 1=exception, -1=validation)
- List/Get serialize data directly via WriteJson
- Create/Update/Delete/Write use WriteInfo for success messages
- Removed WriteResult helper method
- Removed unused using directive

MCP Server Changes:
- List serializes List<NamedRangeInfo> directly
- Read serializes NamedRangeValue directly
- Write/Create/Update/Delete wrap void operations in lambda with dummy return
- All CRUD ops return success message JSON with operation-specific messages
- Delete includes workflowHint about #NAME? errors

Test Changes (12 tests converted, all passing):
- Lifecycle.cs: 4 tests - List accesses data directly, Create/Delete void with verification
- Validation.cs: 6 tests - Parameter validation with Assert.Throws for errors
- Values.cs: 3 tests - Write/Read void/data operations with verification

All layers build successfully with 0 errors, 0 warnings
All 12 NamedRange tests passing (100%)

Phase 3 (NamedRange) complete - 6 Core methods + 12 tests converted

* refactor(conditionalformat): Convert ConditionalFormatting commands to exception pattern

Core Changes:
- IConditionalFormattingCommands: AddRule and ClearRules return void
- All methods throw exceptions on error (InvalidOperationException, ArgumentException)
- Removed OperationResult wrappers, use dummy return 0 for batch.Execute
- Removed unused using directives

CLI Changes:
- ExecuteAddRule/ExecuteClearRules use try-catch with exit codes (0=success, 1=exception, -1=validation)
- WriteInfo for success messages
- Removed WriteResult helper method
- Removed unused using directive

MCP Server Changes:
- AddRule/ClearRules wrap void operations in lambda with dummy return
- Return success message JSON with operation-specific messages
- Keep workflowHints for formatting verification guidance

All layers build successfully with 0 errors, 0 warnings
No tests exist for ConditionalFormatting commands

Phase 4.1 (ConditionalFormatting) complete - 2 Core methods converted

* Refactor: Convert Connection, File, VBA subsystems from OperationResult to exception-throwing pattern

- Connection: IConnectionCommands methods now return void, throw on error
- File: CreateEmpty returns void, throws on error
- VBA: Trust, Import, Delete, Run operations throw exceptions
- CLI layer: Updated error handling for void operations
- MCP layer: Responses serialized as {success: true} for void operations
- Test infrastructure: Updated 14 test helper files to check exceptions

Mutation operations now follow .NET convention of throwing exceptions instead of returning error-wrapped results. Read operations continue returning typed results.

All three layers (Core, CLI, MCP) coordinated for consistent behavior.

* Merge branch 'feature/shared-tool-error-handling' of https://github.com/sbroenne/mcp-server-excel into feature/shared-tool-error-handling

* Refactor: Convert Sheet subsystem from OperationResult to exception-throwing pattern

Convert 12 Sheet mutation methods to void signatures across all layers:
- ISheetCommands: Create, Rename, Copy, Delete, Move, CopyToWorkbook, MoveToWorkbook, SetTabColor, ClearTabColor, SetVisibility, Show, Hide, VeryHide
- SheetCommands (Core): All implementations use batch.Execute() with return 0, exceptions propagate
- SheetCommand (CLI): All void operations wrapped in try-catch with success/error messages
- ExcelWorksheetTool (MCP): All 10 void methods use WithSession() + return 0 + JSON serialization

Production code compiles cleanly. MCP smoke test: PASSED. Tests require separate refactoring for void method assertions.

* Refactor: Convert Table subsystem from OperationResult to exception-throwing pattern (17 void methods, Core+CLI+MCP layers)

- ITableCommands: 17 mutation methods converted to void signatures with exception documentation
- Core layer: 17 implementations across 7 partial files use batch.Execute() return 0 pattern
- CLI layer: 10 void handlers use try-catch-serialize pattern with success/error responses
- MCP layer: 10 void tool methods use try-catch-JSON pattern (fixed 8 broken WithSession<T> calls)
- All production layers compile cleanly: 0 errors, 0 warnings
- MCP smoke test PASSED: all 11 tools working correctly
- Test layer errors (44) deferred: void assertion issues to be fixed separately
- Pattern matches Sheet/Connection/File/VBA subsystem conversions

* feat: Convert PowerQuery subsystem mutation methods to void pattern (Delete, Create, Update, LoadTo, RefreshAll)

* Convert DataModel subsystem to exception-throwing pattern

- Interface: 7 void mutation methods (DeleteMeasure, DeleteRelationship, Refresh (2 overloads), CreateMeasure, UpdateMeasure, CreateRelationship, UpdateRelationship)
- Core: Converted Write.cs (6 mutations) and Refresh.cs (2 methods) to void pattern with batch.Execute((ctx, ct) => { ...code...; return 0; })
- CLI: 7 handlers with try-catch-console JSON output
- MCP: 7 tool methods with try-catch-JSON error handling
- Removed unused Core.Models imports from Write.cs and Refresh.cs
- Build: 0 errors, 0 warnings across Core, CLI, MCP layers

Note: Test failures expected (44 in Core, 50+ in other test files due to void assertion issues) - these are deferred per testing strategy (Rule 14)

* Merge branch 'feature/shared-tool-error-handling' of https://github.com/sbroenne/mcp-server-excel into feature/shared-tool-error-handling

* fix: Complete void test migration - 84/84 errors fixed

Complete migration of 84 test compilation errors to exception-based pattern.
This completes the integration of void Execute infrastructure with test layer updates.

✅ BUILD VERIFIED: 0 errors, 0 warnings
✅ PRE-COMMIT PASSED: All quality gates passing

Test Migrations (84 total):
- Sheet tests: 19 errors (Move, TabColor, Visibility, Lifecycle)
- Helper fixtures: 4 errors (PowerQuery, Table, DataModel, PivotTable)
- PowerQueryCommandsTests: 19 errors (Create, Update, Delete, LoadTo calls)
- DataModelCommandsTests: 12 errors (CreateMeasure, UpdateMeasure, CreateRelationship, DeleteRelationship)
- DataModelTestsFixture: 1 error (var assignment from void CreateMeasure)
- TableCommandsTests: 2 errors (Create calls in tests and fixture)
- PivotTableCommandsTests: 3 errors (Create calls from Table/DataModel)
- PivotTableCommandsTests.OlapFields: 2 errors (CreateMeasure calls)

Pattern Applied (Two types):
1. CS0815 'Cannot assign void': Remove 'var result =' and 'Assert.True(result.Success)' lines
2. Remove unnecessary success checks - void methods throw on error instead

Infrastructure:
- void Execute(Action<ExcelContext, CancellationToken>) in IExcelBatch/ExcelBatch
- Delegates to Execute<T>(Func<...>) returning dummy 0
- Non-breaking enhancement for clean void method support

Verification:
✅ Build: 0 errors, 0 warnings
✅ Pre-commit checks: All passed
  - COM leak detection: 0 leaks
  - Success flag validation: All consistent
  - MCP implementation coverage: 100%
  - MCP server smoke test: Passed
✅ Feature branch active (feature/shared-tool-error-handling)

* docs: Add void test migration completion summary

* refactor: Convert 11 Range void mutations to fire-and-forget pattern across all layers

Complete refactoring of Range command mutations to void pattern:

CORE LAYER (11 void mutations):
- RangeCommands.Search.cs: Replace, Sort
- RangeCommands.Formatting.cs: SetStyle, FormatRange
- RangeCommands.Validation.cs: ValidateRange, RemoveValidation
- RangeCommands.AutoFit.cs: AutoFitColumns, AutoFitRows
- RangeCommands.Advanced.cs: MergeCells, UnmergeCells, SetCellLock

INTERFACE:
- IRangeCommands.cs: All 11 signatures changed from OperationResult to void

MCP TOOL LAYER:
- ExcelRangeTool.cs: All 11 calls updated to use WithSession<object?>() pattern
  * Explicit type parameter resolves CS0411 type inference on void returns
  * Returns { Success = true } JSON directly for all void mutations
  * Lambda formatting fixed (IDE0055 compliance)

CLI LAYER:
- RangeCommand.cs: All 11 command handlers adapted
  * Removed var result = ... assignments
  * Call void methods directly
  * Return { Success = true } JSON on completion

TEST LAYER (14+ files):
- RangeCommandsTests: All test files updated
  * Removed var result = ... assignments
  * Removed Assert.True(result.Success, ...) assertions
  * Void methods throw on failure; silence = success

BUILD STATUS: ✅ Clean - 0 errors, 0 warnings

LEGITIMATE OperationResult METHODS (NOT CONVERTED):
- SetValues, SetFormulas, Copy, SetNumberFormat, AddHyperlink
- These data mutations need validation and result reporting

PATTERN:
- Void mutations: Fire-and-forget with exception-based error handling
- Exceptions propagate naturally through batch.Execute() layer
- No OperationResult wrapping needed for simple write operations

* chore: Remove unused imports and temporary documentation files

- Clean up unused using directives across Table and PivotTable commands
- Remove temporary documentation files
- Maintain code style consistency

* fix: Update MartinCostello.Logging.XUnit package version to 0.7.0

* fix(chart): Suppress CodeQL false positives for dynamic COM interop in Strategy pattern

- Add pragma warning disable CS8604 for all Strategy method calls
- CodeQL cannot verify dynamic Excel COM objects have required methods at compile-time
- All methods verified to exist in both RegularChartStrategy and PivotChartStrategy
- False positives: SetSourceRange, AddSeries, RemoveSeries, GetInfo, GetDetailedInfo
- Addresses code scanning alerts #2631-2635
2025-11-23 17:32:04 +00:00
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
Stefan Broenner 72c968c0ba feat: Add cross-workbook worksheet operations (copy-to-workbook, move-to-workbook) (#231)
Implements GitHub issue #187 - Enable copying and moving worksheets between different Excel workbooks.

**Architecture Changes:**
- Extended IExcelBatch to support multiple workbooks in single Excel.Application instance
- Added Workbooks property (IReadOnlyDictionary<string, dynamic>) and GetWorkbook(string) method
- Modified ExcelBatch constructor to accept string[] workbookPaths and open all in shared COM context
- Updated ExcelSession.BeginBatch to accept params string[] filePaths

**Core Implementation:**
- Added CopyToWorkbook and MoveToWorkbook methods to ISheetCommands
- Implemented using Excel COM Worksheet.Copy and Worksheet.Move APIs
- Extended List() and Create() with optional filePath parameter for multi-workbook scenarios
- Uses batch.GetWorkbook(filePath) to target specific workbook in multi-file batches

**MCP Server:**
- Updated ExcelWorksheetTool to create temporary multi-file batches for cross-workbook operations
- Added comprehensive cross-workbook documentation to tool description
- Updated excel_worksheet.md prompt with workflow examples and guidance

**Tests:**
- Converted 10 cross-workbook tests from error-handling to positive validation
- Updated 18 test files for new ExcelBatch constructor signature (array parameter)
- All 9 cross-workbook integration tests passing

**Documentation:**
- Updated README.md: 13→16 worksheet actions, added cross-workbook capability
- Updated CLI README: Added copy-to-workbook/move-to-workbook examples
- Updated GitHub Pages: 158 operations (fixed inconsistencies), comprehensive action tables
- Updated vscode-extension README: Already correct (16 actions)

**Key Benefits:**
- Single Excel.Application for multiple workbooks = proper COM object sharing
- No RCW isolation issues between batches
- Clean multi-workbook API: ExcelSession.BeginBatch(file1, file2, file3)
- LLMs now have clear guidance on when/how to use cross-workbook operations
2025-11-22 12:45:23 +00:00
Copilot ffbef07a2e Add tests and documentation for Connection Delete action (#228)
* Initial plan

* Add comprehensive tests for Connection Delete action and update documentation

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

* Add MCP Server integration tests for Connection Delete action

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>
2025-11-22 13:31:43 +01:00
Stefan Broenner 76f77a7240 Fix integration tests: Add missing batch-test-static.xlsx file (#225) 2025-11-22 08:41:24 +00:00
Stefan Broenner 9e7d532196 refactor: eliminate exception wrapping across all command layers (205+ catch blocks removed) (#224)
* refactor: centralize Excel shutdown logic and add early path validation

- Extract SaveWorkbookWithTimeout() to eliminate code duplication (~70 lines)
- Create ExcelShutdownService for unified workbook close and Excel quit
- Remove GC.Collect() calls per Microsoft guidance (RCW finalizers handle cleanup)
- Add early path length validation (218 char limit) before Excel COM operations
- Convert COM path errors to PathTooLongException with clear messages
- Update all exception catch blocks to handle nested AggregateException
- Add Microsoft.Extensions.Resilience for COM busy retry with exponential backoff
- Update documentation to reflect batch API patterns and remove deprecated references

Benefits:
- Fail fast: Path validation before spawning Excel process
- DRY: Single shutdown implementation used by ExcelBatch, ExcelSession, FileCommands
- Performance: No forced GC, automatic RCW cleanup
- Resilience: 6-attempt retry for transient COM busy errors
- Clear errors: PathTooLongException → JSON error messages for LLMs

* refactor: remove unnecessary try-catch blocks for cleaner code

* Potential fix for code scanning alert no. 2575: Generic catch clause

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for code scanning alert no. 2576: Generic catch clause

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* refactor: clean up Excel process termination logic in tests

* refactor: update documentation for ExcelSession tests to clarify cleanup process

* Refactor Excel Tool Classes and Tests

- Removed unused variables and comments in ExcelNamedRangeTool, ExcelPowerQueryTool, ExcelRangeTool, ExcelVbaTool, and ExcelWorksheetTool to clean up the code.
- Updated tests in ExcelComSmokeTests, ExcelBatchTests, ExcelSessionTests, and SessionManagerTests to improve readability and maintainability by eliminating unnecessary variable assignments.
- Consolidated sheet command tests into a single file, SheetCommandsTests.Move.cs, and removed redundant tests from the previous SheetCommandsTests.MoveAndCrossWorkbook.cs file.
- Ensured all tests maintain functionality while improving structure and clarity.

* refactor: streamline loading logic in Power Query commands

* refactor: update Power Query refresh methods to enforce timeout and improve error handling

* refactor: remove unused result properties and exception wrapping from PowerQuery commands

- Removed IsRetryable, RetryGuidance, OperationContext from ResultBase
  These fields were never consumed by CLI, MCP Server, or LLM layers

- Refactored PowerQuery commands to let exceptions bubble naturally
  Removed outer try-catch wrapping from 6 partial files:
  - PowerQueryCommands.Create.cs
  - PowerQueryCommands.View.cs
  - PowerQueryCommands.Update.cs
  - PowerQueryCommands.Lifecycle.cs
  - PowerQueryCommands.Refresh.cs
  - PowerQueryCommands.LoadTo.cs

- Pattern: batch.Execute() already captures exceptions via TaskCompletionSource
  No need to wrap at method level. Keep finally blocks for COM cleanup.

Test Results:
- PowerQuery: 14/14 passed
- CLI: 2/2 passed
- Connection: 13/13 passed
- MCP: 44/46 passed (2 pre-existing PivotTable enum failures)
- Build: 0 errors, 0 warnings

Architecture validation confirms sound design:
- Exception propagation works end-to-end
- COM resource cleanup via finally blocks still functions
- No loss of functionality

* refactor: remove exception wrapping from all remaining Core commands

Applied the same pattern across 21 additional command files:
- Connection (3 files)
- VBA (3 files)
- Table (6 files)
- Sheet (4 files)
- Range (4 files)
- DataModel (3 files)
- PivotTable (6 files)
- NamedRange (2 files)
- ConditionalFormat (1 file)

Changes:
- Removed outer try-catch wrappers around batch.Execute() calls
- Preserved all finally blocks for critical COM resource cleanup
- Preserved inner try-catch for specific exception handling
- Exceptions now flow naturally to batch.Execute() via TaskCompletionSource

Statistics:
- 21 files refactored (+ 8 from PowerQuery = 29 total)
- 41 methods updated
- 553 net lines removed (982 deleted, 429 inserted)
- 0 compilation errors
- Build: SUCCESS

Test Results (spot checks):
- PowerQuery: 14/14 PASSED
- Worksheets: 36/36 PASSED

Architecture validated across entire Core command layer.

* refactor: remove all suppressions from RegularPivotTableFieldStrategy.cs

- Removed 11 exception-suppressing catch blocks (Success=false returns)
- Preserved all finally blocks for COM resource cleanup
- Methods refactored: ListFields, AddRowField, AddColumnField, AddValueField,
  AddFilterField, RemoveField, SetFieldName, SetFieldFunction, SetFieldFormat,
  SetFieldFilter, SortField, SetLayout, SetSubtotals, SetGrandTotals
- Exceptions now flow naturally to callers
- Build: 0 errors confirmed
- Architecture validated - batch.Execute() TaskCompletionSource properly receives exceptions

* refactor: remove exception suppressions from OlapPivotTableFieldStrategy.cs

- Removed all exception-suppressing catch blocks (Success=false returns)
- Preserved safe fallback patterns (continue in loop, conditional rethrrows)
- Methods affected: ListFields and related field manipulation methods
- Build: 0 errors confirmed
- 17 safe fallback catches remaining (architectural patterns - KEEP)
- OlapPivotTableFieldStrategy refactoring complete

* refactor: remove exception suppression from PowerQuery commands (21 patterns)

- PowerQueryCommands.LoadTo.cs: 6 patterns removed
  * Parameter validation (targetCellAddress) → ArgumentException
  * Query not found → InvalidOperationException
  * Sheet access, table overlap, cell data validation → InvalidOperationException
  * Removed catch block suppressing Data Model exceptions

- PowerQueryCommands.Update.cs: 4 patterns removed
  * Query name validation → ArgumentException
  * Empty M code validation → ArgumentException
  * Query not found → InvalidOperationException
  * Removed catch block suppressing refresh exceptions

- PowerQueryCommands.View.cs: 2 patterns removed
  * Query name validation → ArgumentException
  * Query not found → InvalidOperationException

- PowerQueryCommands.Refresh.cs: 2 patterns removed
  * Query name validation → ArgumentException
  * Query not found with suggestion → InvalidOperationException

- PowerQueryCommands.Lifecycle.cs: 4 patterns removed
  * GetLoadConfig validation → ArgumentException
  * GetLoadConfig query not found → InvalidOperationException
  * Delete validation → ArgumentException
  * Delete query not found → InvalidOperationException

- PivotTableCommandsTests: 3 tests corrected
  * Fixed GetInfo_NonExistent, Delete_NonExistent to use Assert.Throws
  * Updated CreateFromDataModel_NoDataModel error message expectation

All exceptions now propagate naturally through batch.Execute().
Build: 0 errors, 0 warnings
Tests: All 14 PowerQuery tests pass, 3 PivotTable tests pass

* refactor: remove exception suppression from Range commands (61 patterns)

Converted all error suppression patterns in RangeCommands to proper exception propagation:

**Files Fixed (61 patterns total):**

- RangeCommands.Editing.cs: 21 patterns removed
  * Copy, CopyValues, CopyFormulas: Convert null checks → InvalidOperationException, remove catch blocks
  * InsertCells, DeleteCells, InsertRows, DeleteRows, InsertColumns, DeleteColumns: Convert null checks → InvalidOperationException, remove catch blocks

- RangeCommands.Search.cs: 8 patterns removed
  * Find: Convert null check → InvalidOperationException, remove catch block
  * Replace: Convert null check → InvalidOperationException, remove catch block
  * Sort: Convert null checks + validations → InvalidOperationException/ArgumentException, remove catch block

- RangeCommands.NumberFormat.cs: 8 patterns removed
  * GetNumberFormats, SetNumberFormat: Convert null checks → InvalidOperationException, remove catch blocks
  * SetNumberFormats: Convert null checks + validation errors → InvalidOperationException/ArgumentException, remove catch blocks

- RangeCommands.Hyperlinks.cs: 8 patterns removed
  * AddHyperlink, RemoveHyperlink, ListHyperlinks, GetHyperlink: Convert null checks → InvalidOperationException, remove catch blocks

- RangeCommands.Values.cs: 4 patterns removed
  * GetValues, SetValues: Convert null checks → InvalidOperationException
  * Convert specific COM exceptions (E_OUTOFMEMORY) → throw InvalidOperationException (not suppress)

- RangeCommands.Formulas.cs: 4 patterns removed
  * GetFormulas, SetFormulas: Convert null checks → InvalidOperationException
  * Convert specific COM exceptions (E_OUTOFMEMORY) → throw InvalidOperationException (not suppress)

- RangeCommands.Discovery.cs: 6 patterns removed
  * GetUsedRange, GetCurrentRegion, GetInfo: Convert null checks → InvalidOperationException, remove catch blocks

- RangeHelpers.cs: 2 patterns removed
  * ClearRange helper: Convert null check → InvalidOperationException, remove catch block

**Pattern Applied:**
- Parameter validation (BEFORE batch.Execute()): null → ArgumentException
- Not found / Invalid state (INSIDE batch.Execute()): null → InvalidOperationException
- Specific COM exceptions: Rethrow as InvalidOperationException with context (not suppress)
- Remove all catch blocks that return OperationResult { Success = false }

All exceptions now propagate naturally through batch.Execute().
Build: 0 errors, 0 warnings

* refactor: remove exception suppression from Range commands (61 patterns)

Converted all error suppression patterns in RangeCommands to proper exception propagation:

**Files Fixed (61 patterns total):**

- RangeCommands.Editing.cs: 21 patterns removed
  * Copy, CopyValues, CopyFormulas: Convert null checks → InvalidOperationException, remove catch blocks
  * InsertCells, DeleteCells, InsertRows, DeleteRows, InsertColumns, DeleteColumns: Convert null checks → InvalidOperationException, remove catch blocks

- RangeCommands.Search.cs: 8 patterns removed
  * Find: Convert null check → InvalidOperationException, remove catch block
  * Replace: Convert null check → InvalidOperationException, remove catch block
  * Sort: Convert null checks + validations → InvalidOperationException/ArgumentException, remove catch block

- RangeCommands.NumberFormat.cs: 8 patterns removed
  * GetNumberFormats, SetNumberFormat: Convert null checks → InvalidOperationException, remove catch blocks
  * SetNumberFormats: Convert null checks + validation errors → InvalidOperationException/ArgumentException, remove catch blocks

- RangeCommands.Hyperlinks.cs: 8 patterns removed
  * AddHyperlink, RemoveHyperlink, ListHyperlinks, GetHyperlink: Convert null checks → InvalidOperationException, remove catch blocks

- RangeCommands.Values.cs: 4 patterns removed
  * GetValues, SetValues: Convert null checks → InvalidOperationException
  * Convert specific COM exceptions (E_OUTOFMEMORY) → throw InvalidOperationException (not suppress)

- RangeCommands.Formulas.cs: 4 patterns removed
  * GetFormulas, SetFormulas: Convert null checks → InvalidOperationException
  * Convert specific COM exceptions (E_OUTOFMEMORY) → throw InvalidOperationException (not suppress)

- RangeCommands.Discovery.cs: 6 patterns removed
  * GetUsedRange, GetCurrentRegion, GetInfo: Convert null checks → InvalidOperationException, remove catch blocks

- RangeHelpers.cs: 2 patterns removed
  * ClearRange helper: Convert null check → InvalidOperationException, remove catch block

**Pattern Applied:**
- Parameter validation (BEFORE batch.Execute()): null → ArgumentException
- Not found / Invalid state (INSIDE batch.Execute()): null → InvalidOperationException
- Specific COM exceptions: Rethrow as InvalidOperationException with context (not suppress)
- Remove all catch blocks that return OperationResult { Success = false }

All exceptions now propagate naturally through batch.Execute().
Build: 0 errors, 0 warnings

* refactor(core): Convert DataModel validation errors to exceptions (31 patterns)

- DataModelCommands.Write.cs: 18 patterns fixed
  - DeleteMeasure, DeleteRelationship, CreateMeasure, UpdateMeasure
  - CreateRelationship, UpdateRelationship
  - NoDataModelTables, MeasureNotFound, TableNotFound, RelationshipNotFound
  - All validation errors before batch.Execute() → InvalidOperationException

- DataModelCommands.Read.cs: 10 patterns fixed
  - ListMeasures, Read, ListRelationships, ListColumns, ReadTable, ReadInfo
  - NoDataModelTables, MeasureNotFound, TableNotFound
  - All validation errors → InvalidOperationException

- DataModelCommands.Refresh.cs: 2 patterns fixed
  - NoDataModelTables, TableNotFound → InvalidOperationException
  - Kept Model.Refresh() catch (line 71) - valid recoverable COM exception

Part of exception propagation refactoring. Let batch.Execute() handle
exceptions via TaskCompletionSource for proper STA thread propagation.

Related: PowerQuery (SHA cbf4441), Range (SHA 1a0cb35)

* refactor(core): Convert Table validation errors to exceptions (15/56 patterns - Part 1)

- TableCommands.Data.cs: 2 patterns fixed
  - Append: TableNotFound, NoData validation

- TableCommands.StructuredReferences.cs: 2 patterns fixed
  - GetStructuredReference: TableNotFound
  - Removed outer catch block

- TableCommands.DataModel.cs: 5 patterns fixed
  - AddToDataModel: TableNotFound, TableInDataModel (2x), Add2Exception
  - Removed outer catch block

- TableCommands.Lifecycle.cs: 6 patterns fixed
  - Create: SheetNotFound, TableExists
  - Rename: TableNotFound, NewNameExists
  - Delete: TableNotFound
  - Read: TableNotFound

Part of exception propagation refactoring. Remaining 41 patterns in:
Filters (11), Structure (9), Columns (8), Sort (8), NumberFormat (7)

Related: PowerQuery (SHA cbf4441), Range (SHA 1a0cb35), DataModel (SHA 64929e4)

* refactor(core): Convert Table validation errors to exceptions (30/56 patterns - Part 2)

- TableCommands.NumberFormat.cs: 7 patterns fixed
  - GetColumnNumberFormat, SetColumnNumberFormat helper methods
  - TableNotFound, ColumnNotFound, NoDataRows validations
  - Removed catch blocks

- TableCommands.Sort.cs: 8 patterns fixed
  - Sort (single column): TableNotFound, ColumnNotFound
  - Sort (multi column): NoSortColumns, TooManySortColumns, TableNotFound, ColumnNotFound
  - Removed catch blocks

Total Table progress: 30/56 patterns complete. Remaining: 26 patterns in
Filters (10), Columns (7), Structure (9)

Related: PowerQuery (SHA cbf4441), Range (SHA 1a0cb35), DataModel (SHA 64929e4), Table Part 1 (SHA dce889a)

* refactor(core): Convert Table validation errors to exceptions (56/56 patterns - Part 3)

Complete final Table command files with exception propagation pattern:
- Columns: 7 patterns (AddColumn, RemoveColumn, RenameColumn)
- Structure: 9 patterns (Resize, ToggleTotals, SetColumnTotal, SetStyle)
- Filters: 10 patterns (ApplyFilter x2, ClearFilters, GetFilters)

All Table validation errors now throw InvalidOperationException before batch.Execute().
All catch blocks removed - batch.Execute() handles exceptions via TaskCompletionSource.

Progress: 169 patterns complete (PowerQuery 21, Range 61, DataModel 31, Table 56)
Remaining: 48 patterns (Sheet 12, VBA & Other 36)

* refactor(core): Convert Sheet validation errors to exceptions (12 patterns)

Convert all Sheet command validation errors to exceptions:
- Lifecycle: 6 patterns (parameter validation, SheetNotFound checks)
- TabColor: 4 patterns (RGB validation, SheetNotFound checks)
- Visibility: 2 patterns (SheetNotFound checks)

All Sheet validation errors now throw ArgumentException/InvalidOperationException before batch.Execute().

Progress: 181 patterns complete (PowerQuery 21, Range 61, DataModel 31, Table 56, Sheet 12)
Remaining: 36 patterns (VBA 14, NamedRange 9, Connection 14, PowerQuery.Create 3)

* refactor(core): Convert PowerQuery.Create validation errors to exceptions (3 patterns)

Convert validation errors in PowerQueryCommands.Create to exceptions:
- Empty query name \u2192 ArgumentException
- Empty M code \u2192 ArgumentException
- Existing query \u2192 InvalidOperationException

Progress: 184 patterns complete (PowerQuery 24, Range 61, DataModel 31, Table 56, Sheet 12)
Remaining: 33 patterns (VBA 14, NamedRange 9, Connection 14) - investigating pattern types

* refactor(core): Convert VBA validation errors to exceptions (10 patterns)

Convert VBA command validation errors to exceptions:
- Lifecycle: 7 patterns (VBA file validation, trust checks, module not found)
- Operations: 3 patterns (Run/Delete validation, module not found)

Note: Kept 7 safe catch blocks for COM trust exceptions (per Rule 1b).

Progress: 194 patterns complete (PowerQuery 24, Range 61, DataModel 31, Table 56, Sheet 12, VBA 10)
Remaining: 23 patterns (NamedRange 9, Connection 14)

* refactor(core): Convert Connection, NamedRange, PowerQuery, and VBA validation errors to exceptions (20 patterns)

**Changes:**
- ConnectionCommands.Lifecycle.cs: 5 patterns (View, Refresh, Delete - connection not found + PowerQuery redirect checks)
- ConnectionCommands.Operations.cs: 4 patterns (LoadTo, Test - connection not found + PowerQuery redirect + empty connection string)
- ConnectionCommands.Properties.cs: 5 patterns (GetProperties, SetProperties - connection not found + PowerQuery redirect + removed 2 catch-all blocks)
- NamedRangeCommands.Operations.cs: 9 patterns (Write, Read, Create, Update, Delete - parameter not found + validation checks converted to ArgumentException)
- PowerQueryCommands.Lifecycle.cs: 2 patterns (Unload - query name validation + query not found)
- VbaCommands.Operations.cs: 1 pattern (Run - VBA file validation before batch.Execute)

**Pattern Conversion:**
- Validation BEFORE batch.Execute → ArgumentException
- Validation INSIDE batch.Execute → InvalidOperationException
- Catch-all Exception blocks → Removed entirely (let batch.Execute handle)

**Safe Patterns Preserved (5 total):**
- DataModelCommands.Refresh.cs: Fallback logic when Model.Refresh() unsupported
- PowerQueryCommands.Refresh.cs: COM exception handling for refresh errors (2)
- VbaCommands.Lifecycle.cs: COM trust disabled during operation (2)

**Progress:**
- Completed: 211 patterns across 7 commits
- Remaining: 5 safe exception handlers (intentionally kept)
- Build: Successful, 0 warnings, 0 errors

* refactor(core): Convert 2 remaining VBA Lifecycle validation errors to exceptions

**Changes:**
- VbaCommands.Lifecycle.cs: 2 patterns
  - List: VBA trust check before batch.Execute → InvalidOperationException
  - Update: Module not found inside batch.Execute → InvalidOperationException

**Pattern Conversion:**
- Validation BEFORE batch.Execute → InvalidOperationException (trust check is pre-condition)
- Validation INSIDE batch.Execute → InvalidOperationException (module not found)

**Note:** These 2 patterns were fixed in same session as SHA 35def63 but accidentally not staged with that commit. Including them now for completeness.

**Progress:**
- Total completed: 217 patterns across 8 commits
- Remaining: 5 safe exception handlers (intentionally kept)
- Build: Successful, 0 warnings, 0 errors

* fix(mcp-server): add missing PivotTableAction enum mappings

Adds ToActionString mappings for 6 PivotTableAction values:
- GroupByDate → 'group-by-date'
- GroupByNumeric → 'group-by-numeric'
- CreateCalculatedField → 'create-calculated-field'
- SetLayout → 'set-layout'
- SetSubtotals → 'set-subtotals'
- SetGrandTotals → 'set-grand-totals'

Fixes test failure in AllActionEnums_HaveCompleteToActionStringMappings.

Test results:
- MCP Server: 5/5 tests passed
- CLI: 2/2 tests passed

* feat(cli): add 6 missing PivotTable actions for full Core parity

Adds CLI support for advanced PivotTable operations:
- group-by-date: Group date/time fields (Days, Months, Quarters, Years)
- group-by-numeric: Create numeric range groups with interval
- create-calculated-field: Custom formulas for derived fields
- set-layout: Compact/Tabular/Outline layout forms
- set-subtotals: Show/hide subtotals for row fields
- set-grand-totals: Control row/column grand totals

Implementation:
- Added 6 new actions to PivotTableCommand switch statement
- Implemented 6 execution methods with validation
- Added 9 new command options to Settings class
- Added TryParseDateGroupingInterval helper method

Coverage: PivotTable CLI now has 25/25 actions (100% parity with Core/MCP)

* feat(cli): add 28 missing Range actions for full Core parity

Adds comprehensive Range CLI support:

INSERT/DELETE OPERATIONS (6):
- insert-cells: Insert blank cells with shift direction
- delete-cells: Delete cells with shift direction
- insert-rows: Insert entire rows
- delete-rows: Delete entire rows
- insert-columns: Insert entire columns
- delete-columns: Delete entire columns

FIND/REPLACE OPERATIONS (2):
- find: Search for values/formulas with options
- replace: Replace text/values with options

SORT OPERATION (1):
- sort: Multi-column sorting with headers support

RANGE QUERIES (3):
- get-used-range: Get worksheet's used range
- get-current-region: Get contiguous data block
- get-info: Get range information (address, dimensions)

NUMBER FORMAT OPERATIONS (3):
- get-number-formats: Get format codes (2D array)
- set-number-format: Set uniform format for range
- set-number-formats: Set per-cell formats (2D array)

STYLE OPERATIONS (2):
- get-style: Get built-in style name
- set-style: Apply built-in Excel style

FORMATTING OPERATION (1):
- format-range: Visual formatting (font, fill, border, alignment)

VALIDATION OPERATIONS (3):
- validate-range: Add data validation rules
- get-validation: Get validation settings
- remove-validation: Remove validation

AUTO-FIT OPERATIONS (2):
- autofit-columns: Auto-fit column widths
- autofit-rows: Auto-fit row heights

MERGE OPERATIONS (3):
- merge-cells: Merge cells into single cell
- unmerge-cells: Unmerge previously merged cells
- get-merge-info: Check if range has merged cells

CELL LOCK OPERATIONS (2):
- set-cell-lock: Lock/unlock cells
- get-cell-lock: Get cell lock status

Implementation:
- Added 28 switch case entries
- Implemented 28 execution methods with validation
- Added 4 helper methods (direction parsers, format loaders)
- Added 49 new command options to Settings class

Coverage: Range CLI now has 42/42 actions (100% parity with Core/MCP)

* feat(cli): add 4 missing PowerQuery actions for full Core parity

Adds PowerQuery CLI support for:
- delete: Remove Power Query from workbook
- refresh: Update query data with configurable timeout
- get-load-config: Get current load destination settings
- refresh-all: Refresh all Power Queries in workbook

Implementation:
- Added 4 switch case entries
- Implemented 4 execution methods
- Added --refresh-timeout option for refresh action
- Updated help message with all 9 actions

Coverage: PowerQuery CLI now has 9/9 actions (100% parity with Core/MCP)

* feat(cli): add action aliases for DataModel and Table (full Core parity)

DataModel CLI: Already complete with 14/14 actions
- All Core methods already exposed with proper aliases
- No changes needed

Table CLI: Add action aliases for consistency
- Added 'read' alias for 'get' (table info)
- Added 'get-column-number-format' alias for 'get-column-format'
- Added 'set-column-number-format' alias for 'set-column-format'

Implementation:
- Updated switch statement to support both naming conventions
- Maintains backward compatibility with existing action names

Coverage: Table CLI now has 23/23 actions (100% parity with Core/MCP)

---------

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-11-21 17:32:24 +01:00
Stefan Broenner ae71b7cff9 feat(pivottable): Complete PivotTable expansion (Issue #219) (#223)
* feat(pivottable): Add date grouping by Days/Months/Quarters/Years (Task 1 of Issue #219)

Implements GroupByDate operation for PivotTable fields with support for all 4 date intervals.
Excel automatically creates hierarchical groupings (e.g., Months + Years) for proper time-based analysis.

CRITICAL DISCOVERY - NumberFormat Requirement:
- Source data MUST be formatted with date NumberFormat BEFORE creating PivotTable
- Without proper formatting, dates stored as serial numbers (e.g., 45672) with 'Standard' format
- Excel silently fails to group plain numbers - grouping requires date-formatted data
- Solution: Apply NumberFormat = 'm/d/yyyy' to source range before PivotTable creation

Implementation:
- Added DateGroupingInterval enum (Days, Months, Quarters, Years)
- Implemented GroupByDate in RegularPivotTableFieldStrategy using Range.Group()
- Uses PivotField.DataRange.Cells[1,1] for single cell grouping
- Periods array: [Seconds, Minutes, Hours, Days, Months, Quarters, Years]
- Hierarchical grouping: Months/Quarters automatically include Years
- MCP Server: Added GroupByDate action to ExcelPivotTableTool with dateGroupingInterval parameter

Infrastructure Changes:
- Added xUnit logging support via MartinCostello.Logging.XUnit package
- Added IExcelBatch.Logger property with proper STA thread affinity
- Logger passed through batch operations for diagnostics

Test Coverage (4 new tests, all passing):
- GroupByDate_DaysInterval_CreatesDailyGroups
- GroupByDate_MonthsInterval_CreatesMonthlyGroups
- GroupByDate_QuartersInterval_CreatesQuarterlyGroups
- GroupByDate_YearsInterval_CreatesYearlyGroups

All 38 PivotTable tests passing.

Technical Details:
- Date serial: 45672 (Double) = 2025-01-15 (days since 1900-01-01)
- DataRange for Row/Column fields = 'Items in the field'
- Group() called on single cell, not entire range
- Error logging preserved with #pragma CA1848 suppression

Documentation:
- XML docs on interface and implementation with NumberFormat requirement
- Code examples showing proper date formatting

Related: #219 (Task 1 complete)

* feat(pivottable): Add numeric grouping + remove misleading Async naming (Task 2 of Issue #219)

Implements GroupByNumeric operation for numeric field range grouping.
Creates groups like 0-100, 100-200, 200-300 for age groups, price ranges, score bands.

Implementation:
- Uses Range.Group() with Start, End, By parameters
- By parameter specifies interval size (e.g., 100)
- Start/End nullable → null = auto-detect field min/max
- Periods parameter ignored for numeric fields (only for dates)
- Type casting required: double? → object for COM interop
- VB.NET compatibility: Renamed 'end' parameter to 'endValue'

BREAKING CHANGE (Code Quality Improvement):
- Removed misleading 'Async' suffix from 21 synchronous methods in ExcelPivotTableTool
- Methods are synchronous (no async/await/Task) but were incorrectly named
- User observation: 'why do we have Async - everything is Sync!' (correct!)
- Affected: List, Read, Create*, Delete, Refresh, *Field, GroupBy* methods
- Impact: Code now accurately reflects synchronous implementation
- No API change: Method names were internal/private

Documentation Updates:
- Rewrote mcp-server-guide.instructions.md to remove all Async references
- Clarified that all action methods are synchronous
- Tool signatures are 'async Task<string>' only for MCP SDK requirements
- Updated all code examples to show synchronous patterns

Test Coverage (3 new tests, all passing):
- GroupByNumeric_AutoRange_CreatesNumericGroups (interval=100, auto min/max)
- GroupByNumeric_CustomRange_CreatesNumericGroups (0-1000, interval=200)
- GroupByNumeric_SmallInterval_CreatesFineGrainedGroups (interval=50)
- Fixed aggregation function: Use AggregationFunction.Count for text fields

Technical Details:
- Type casting: start.HasValue ? (object)start.Value : true
- COM interop: Excel expects object type for Group() parameters
- VB.NET interop: 'end' keyword conflict → renamed to 'endValue'
- OLAP: Not supported (returns clear error with Power Pivot guidance)

All 41 PivotTable tests passing (38 existing + 3 new).

Related: #219 (Task 2 complete)

* feat(pivottable): Add calculated fields with formulas

Implements Task 3 of Issue #219: CreateCalculatedField operation

FEATURES:
- Regular PivotTables: Full support via CalculatedFields.Add() API
- OLAP PivotTables: NotSupported (use DAX measures instead)
- Formula syntax: =FieldName1 operator FieldName2 (e.g., =Revenue-Cost)
- Operators: + - * / ^ ()

IMPLEMENTATION:
- IPivotTableFieldStrategy: CreateCalculatedField interface method
- RegularPivotTableFieldStrategy: Uses pivot.CalculatedFields().Add()
- OlapPivotTableFieldStrategy: Returns NotSupported with DAX workflow hint
- PivotTableCommands.CalculatedFields.cs: Routes to correct strategy
- PivotTableAction.CreateCalculatedField: New enum value
- ExcelPivotTableTool: MCP Server integration with formula parameter
- PivotFieldResult: Added Formula property for result tracking

TESTS:
- 4 new regular PivotTable tests (multiplication, subtraction, complex, addition)
- 1 new OLAP test using DataModelTestsFixture
- Tests cover: formulas with different operators and parentheses
- OLAP test verifies NotSupported behavior with proper error messages

COMPATIBILITY:
- All 41 existing PivotTable tests passing (no regressions)
- Total: 46 passing tests (41 existing + 5 new)

Closes Task 3 of #219

* feat(pivottable): Add layout and subtotals control (Task 4 of Issue #219)

Implements Task 4 of Issue #219: SetLayout and SetSubtotals operations

FEATURES:
- Layout control: Compact (default), Tabular, Outline forms
- Subtotals control: Show/hide automatic subtotals per field
- Full support for both regular and OLAP PivotTables

LAYOUT FORMS:
- Compact (0): All row fields in single column with indentation
- Tabular (1): Each field in separate column, subtotals at bottom
- Outline (2): Each field in separate column, subtotals at top

IMPLEMENTATION:
- IPivotTableFieldStrategy: SetLayout and SetSubtotals interface methods
- RegularPivotTableFieldStrategy: Uses RowAxisLayout() and field.Subtotals[1]
- OlapPivotTableFieldStrategy: Full support for both operations
- PivotTableCommands.Layout.cs: Routes to correct strategy
- PivotTableCommands.Subtotals.cs: Routes to correct strategy
- PivotTableAction: SetLayout and SetSubtotals enum values
- ExcelPivotTableTool: MCP Server integration with layout and subtotalsVisible parameters

TESTS:
- 6 new tests covering all layout forms and subtotals scenarios
- Tests for both regular and OLAP PivotTables
- Round-trip verification tests

COMPATIBILITY:
- All 46 existing PivotTable tests passing (no regressions)
- Total: 52 passing tests (46 existing + 6 new)

CLOSES #219: All 4 tasks complete
- Task 1: Date grouping (committed 52d1a6d)
- Task 2: Numeric grouping (committed 2d58a45)
- Task 3: Calculated fields (committed 6b6d683)
- Task 4: Layout & Subtotals (this commit)

Issue #219 complete - PivotTable automation fully expanded

* feat(pivottable): Add grand totals control (Task 5 of Issue #219)

Implements feature #8 from Issue #219: SetGrandTotals operation for independent row/column grand totals control in PivotTables.

FEATURES:
- Row grand totals control: Show/hide bottom summary row
- Column grand totals control: Show/hide right summary column
- Independent control: Configure row and column separately
- Full support: Both regular and OLAP PivotTables

IMPLEMENTATION:
- IPivotTableFieldStrategy: SetGrandTotals interface method using pivot.RowGrand/ColumnGrand properties
- RegularPivotTableFieldStrategy: Direct COM property assignment
- OlapPivotTableFieldStrategy: Same COM properties (full OLAP support)
- PivotTableCommands.GrandTotals.cs: Routes to appropriate strategy via factory
- PivotTableAction: SetGrandTotals enum value added
- ExcelPivotTableTool: MCP Server integration with showRowGrandTotals/showColumnGrandTotals parameters

TESTS:
- 6 new tests covering all show/hide combinations
- Test scenarios: show both, hide both, show row only, show column only, multiple sequential changes, round-trip persistence
- All tests passing (58 total: 52 existing + 6 new)

VERIFICATION:
- Build: 0 warnings, 0 errors
- Tests: 58/58 passing (all PivotTable tests)
- Pre-commit: All checks passed (COM leaks, coverage, naming, switch completeness, success flag, MCP smoke test)

CLOSES #219: All required features complete
- Priority 1 (Tasks 1-4 from commits 2417b84, 3cd4a15, c93e44b, 4826ca5): Date grouping, numeric grouping, calculated fields, layout & subtotals ✅
- Feature #8 (Task 5 - this commit): Grand totals control ✅
- Features #6-7 not needed per requirements (OLAP drill, connection management)

* docs: Update operation counts and shorten release notes for Issue #219

- Updated PivotTable actions: 20 → 21 (added SetGrandTotals operation)
- Updated total operations: 163 → 164, total actions: 155 → 156
- Added CHANGELOG entry with Task 5 features (grand totals, grouping, calculated fields, layout/subtotals)
- Shortened release workflow notes ~70% to reduce redundancy with main README
- Files updated: README.md, vscode-extension/README.md, gh-pages/index.md, ExcelMcp.McpServer/README.md, CHANGELOG.md, release-mcp-server.yml

* Merge remote-tracking branch 'origin/main' into feature/pivottable-expansion-219
2025-11-20 18:16:30 +00:00
Copilot 42f01582bc feat: Support adding pre-existing DAX measures to OLAP PivotTables (#221)
* Initial plan

* feat: Support adding pre-existing measures to OLAP PivotTables

- AddValueField now detects if fieldName refers to existing measure
- Supports measure formats: "Name", "[Measures].[Name]", or CubeField name
- Mode 1: Add existing measure (new) - just set Orientation = xlDataField
- Mode 2: Create measure from column (existing) - auto-create DAX measure
- Added IsExistingMeasure() helper to check Data Model measures
- Added 2 new tests for pre-existing measure scenarios

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

* docs: Update documentation for OLAP add-value-field dual mode support

- Updated IPivotTableCommands.cs XML comments
- Updated excel_pivottable.md with OLAP modes explanation
- Updated ExcelPivotTableTool.cs description attribute
- Clarified difference between existing measure vs auto-create modes
- Added workflow guidance for both scenarios

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

* fix: Increase Excel COM cleanup timeout from 30s to 60s

- Changed Join() timeout in ExcelBatch.Dispose() from 30 to 60 seconds
- Updated log messages and exception text to reflect new timeout
- Addresses intermittent test failures in SessionManagerTests

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>
2025-11-20 18:26:06 +01:00
Stefan Broenner 7c51ebbcab feat: Full CRUD support for OLAP PivotTable value fields (#217) (#218)
* feat: Full CRUD support for OLAP PivotTable value fields (#217)

Implements complete CRUD operations for OLAP PivotTable value fields:

CREATE:
- AddValueField auto-creates DAX measures with proper aggregation
- Supports SUM, COUNT, AVERAGE, MIN, MAX functions
- Handles both numeric and non-numeric columns

UPDATE:
- SetFieldFunction: Change aggregation function by modifying DAX formula
- SetFieldFormat: Change number format via FormatInformation property
  * Currency formats ($#,##0.00)
  * Percentage formats (0.00%)
  * Decimal formats (#,##0.00)
  * Whole number formats (#,##0)

READ:
- ListFields: Returns all fields including value fields with measures
- Field info includes measure details (formula, format)

DELETE:
- RemoveField: Deletes measures when removing value fields

Key Implementation:
- ParseDaxFormula/GenerateDaxFormula for formula manipulation
- ModifyFormatObject for in-place format property modification
- FormatInformation uses GET-AND-MODIFY pattern (not assignment)

Tests: All 7 OLAP PivotTable tests passing (2m 34s)
- 2 CREATE tests (SUM, COUNT aggregations)
- 1 UPDATE function test
- 1 UPDATE format test
- 3 other field operation tests

Closes #217

* style: Update padding and font sizes for improved layout in hero section and content area
2025-11-20 06:14:20 +00:00
Stefan Broenner a6672c8ffb Fix #215: Add helpful error message for invalid excel_file action (#216)
- Add specific catch block for ArgumentException containing 'action'
- Return structured JSON with:
  - Clear error message listing valid actions
  - Array of valid action values
  - Workflow hint explaining correct save pattern
- Update tool [Description] to warn about missing 'Save' action
- Update excel_file.md prompt to document session lifecycle
- Add regression test for error message clarity

Fixes unhelpful 'An error occurred invoking excel_file' message when
LLMs attempt to use invalid action values like 'Save' instead of the
correct 'Close' with save=true parameter.
2025-11-20 03:51:21 +00:00
Stefan Broenner 48c7b58ee7 Fix SessionManager disposal bug (issue #209 Phase 2 - 1 of 21) (#212)
* Update package versions and clean up unnecessary usings in tests

* Fix disposal bug in SessionManager.CreateSession (issue #209 Phase 2)

Implements try-finally with null sentinel pattern to ensure IExcelBatch is disposed on error paths.

BEFORE: If TryAdd() threw exception, batch leaked.
AFTER: Batch disposed in finally block unless successfully added to dictionary (ownership transfer via batch = null).

Tests: All 25 SessionManager tests pass (3min 12sec).

Relates to issue #209 - cs/dispose-not-called-on-throw alert.

---------

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-11-20 04:24:23 +01:00
Stefan Broenner 9d9d10aa5c Remove Save action and add save parameter to Close (#207) (#208)
- Remove FileAction.Save from enum (breaking change)
- Add save parameter to CloseSession (default: false)
- Make Close action atomic: saves then closes when save=true
- Update SessionManager.CloseSession to accept save parameter
- Remove separate SaveSession method (no longer needed)
- Update tool description to reflect explicit save requirement
- Update all tests to use new CloseSession signature
- Fix CLI SessionService to throw NotSupportedException for Save

BREAKING CHANGE: LLMs must now explicitly pass save:true to persist changes.
This prevents race conditions and makes the save operation atomic with close.

Fixes #207
2025-11-19 18:39:08 +00:00
Stefan Broenner 11c10d1ce1 Refactor FileCommands.CreateEmpty to bypass batch API (#205) (#206)
- Replace ExcelSession.CreateNew() with direct COM automation
- Add CreateNewWorkbookOnStaThread() for lightweight file creation
- Remove session overhead and metadata comment injection
- Improve performance by avoiding batch API for simple operations
- Remove unused ExcelSession import

Fixes #205
2025-11-19 09:21:41 +00:00
Stefan Broenner fc9a78d7aa Add table style completions and presets for LLM discoverability (#203)
Fixes #202

## Changes

### 1. Table Style Completions
- Created table_styles.md with 60+ preset table styles
- Added tableStyle parameter handler to ExcelCompletionHandler
- Provides autocomplete for Light (1-21), Medium (1-28), Dark (1-11) styles

### 2. Enhanced Prompt Documentation
- Expanded excel_table.md with style categories and naming patterns
- Added popular style recommendations (Medium2, Medium9, Light9, Dark1)
- Documented style behavior and empty string behavior

### 3. TableStylePresets Class
- Created TableStylePresets.cs mirroring NumberFormatPresets pattern
- Documented 23+ common table styles as constants with descriptions
- Provides IntelliSense for developers

### 4. Updated Tests
- Updated test files to use TableStylePresets.Medium2 constant
- Added CompletionHandlerTests for autocomplete verification
- All 22 tests pass (18 table + 4 completion tests)

## Test Results
- Build: 0 warnings, 0 errors
- Feature=Tables: 18 tests passed
- CompletionHandler: 4 tests passed

## Benefits
- LLMs get autocomplete suggestions for table styles
- Consistent with existing NumberFormatPresets/PivotTableStylePresets
- Better developer experience (IntelliSense)
- Complete documentation for table styling
2025-11-19 05:23:06 +00:00
Stefan Broenner 809f2555ee Fix: Use 1-based arrays for Excel COM range operations (#200)
Fixes #199

## Root Cause
SetFormulas and SetValues were creating 0-based C# arrays, but Excel COM
requires 1-based arrays for multi-cell range assignments. This caused
E_OUTOFMEMORY (0x8007000E) errors with misleading 'out of memory' message.

## Changes
- RangeCommands.SetFormulas: Use Array.CreateInstance with [1,1] lower bounds
- RangeCommands.SetValues: Use Array.CreateInstance with [1,1] lower bounds
- Added regression test: SetFormulas_WideHorizontalRange_NoOutOfMemoryError
- Added regression test: SetValues_WideHorizontalRange_NoOutOfMemoryError

## Test Results
All 62 Range tests pass (60 existing + 2 new regression tests)

## Impact
- Before: Multi-cell range operations failed with cryptic error
- After: All range operations work correctly
- Backwards compatible: All existing tests pass
2025-11-19 04:58:30 +00:00
Stefan Broenner 0eb11c04e9 Remove redundant QueryTable and ListExcelSources features (#197)
* Update README to streamline API safety section and enhance clarity

* Update robots.txt to enhance sitemap visibility and prioritize crawling for Googlebot and Bingbot

* Remove obsolete PowerQuery integration tests for LoadTo and timeout scenarios

* Refactor using directives across multiple command files for consistency

* Remove redundant ListExcelSources and Unload methods (#133)

Removed ListExcelSources method from PowerQuery commands as it duplicates
functionality already available via separate excel_table(list) and
excel_namedrange(list) tool calls. LLMs can easily chain these operations.

Also removed Unload method as the interface signature was removed during
earlier refactoring but enum/tool routing remained.

**Changes:**
- Removed IPowerQueryCommands.ListExcelSources() interface method
- Removed PowerQueryCommands.ListExcelSources() implementation (~95 lines)
- Removed PowerQueryAction.ListExcelSources enum value
- Removed action mapping for 'list-excel-sources' from ActionExtensions
- Removed MCP Server tool routing for ListExcelSources (~15 lines)
- Removed PowerQueryAction.Unload enum value
- Removed action mapping for 'unload' from ActionExtensions
- Removed MCP Server tool routing for Unload (~20 lines)
- Converted 10 PowerQuery tests to inline M code (removed .pq file dependencies)

**Total cleanup:** ~140 lines removed

**Related to #133:** Code cleanup discovered both bugs already fixed:
- Bug #1 (Column Preservation): Tests pass - Update handles column changes
- Bug #2 (ListObject Accumulation): Delete() removes ListObjects properly
- All regression tests passing (2/2)

* Remove redundant QueryTable functionality

QueryTable functionality duplicates existing Power Query + Table + Connection
tool capabilities. LLMs can compose workflows from existing tools without
needing a separate QueryTable abstraction.

**Redundancy Analysis:**
- CreateFromQuery → excel_powerquery(action: 'create', loadDestination: 'worksheet')
- CreateFromConnection → excel_connection(action: 'loadto')
- List → excel_table(list) + excel_powerquery(list)
- Refresh → excel_powerquery(refresh) or excel_connection(refresh)
- Delete → excel_powerquery(delete) or excel_table(delete)
- UpdateProperties → Rarely needed, can be set during creation

**Files Deleted:**
- src/ExcelMcp.Core/Commands/QueryTable/ directory (IQueryTableCommands.cs, QueryTableCommands.cs, QueryTableCommands.Lifecycle.cs)
- src/ExcelMcp.Core/Models/QueryTableTypes.cs
- src/ExcelMcp.CLI/Commands/QueryTable/ directory
- src/ExcelMcp.McpServer/Tools/ExcelQueryTableTool.cs
- tests/ExcelMcp.Core.Tests/Integration/Commands/QueryTable/ directory (4 test files)
- src/ExcelMcp.McpServer/Prompts/Content/excel_querytable.md
- specs/QUERYTABLE-SUPPORT-SPECIFICATION.md

**Code Changes:**
- Removed QueryTableAction enum from ToolActions.cs
- Removed ToActionString mapping from ActionExtensions.cs
- Removed CLI command registrations from Program.cs
- Updated tool count: 12 → 11 in all README files
- Updated action count: 163 → 155 in all README files

**Total cleanup:** ~800 lines removed (Core: ~400, CLI: ~150, MCP: ~100, Tests: ~150)

**Same rationale as ListExcelSources removal:** LLMs don't need convenience
wrappers - they can chain operations from focused, single-purpose tools.

* Update documentation to remove QueryTable references

- GitHub Pages: Update tool count (12→11) and action count (163→155)
- Copilot instructions: Remove QueryTable from architecture patterns
- MCP prompts: Remove QueryTable guidance from tool selection, user patterns, server quirks
- MCP prompts: Update excel_connection and excel_powerquery to remove QueryTable references
- Specs: Remove QueryTableTool from session redesign tracking
- ComInterop: Remove unused FindQueryTable() helper (~70 lines)
- Delete ExcelQueryTablePrompts.cs (no longer needed)
- VS Code extension: Update dev dependencies (TypeScript types, eslint)
2025-11-18 17:58:43 +00:00
Stefan Broenner 14fbfe2247 Fix MCP server crashes and CreateEmpty workflow failures (#192) (#193)
Three critical fixes:

1. COM Cleanup Hardening (ExcelBatch.cs)
   - Wrap workbook.Close() and excel.Quit() in try/catch blocks
   - Catch COMException and MissingMemberException
   - Log warnings instead of crashing server
   - Fixes: RPC_E_DISCONNECTED (0x80010108) unhandled exceptions

2. Add Error Messages to Worksheet Tool (ExcelWorksheetTool.cs)
   - List action now includes errorMessage in JSON response
   - Create action now includes errorMessage in JSON response
   - LLMs can now diagnose failures properly

3. Fix CreateEmpty Save (FileCommands.cs)
   - Call ctx.Book.Save() before batch disposal
   - Ensures Sheet1 rename and comment are persisted
   - Fixes: corrupted workbook state after CreateEmpty

Tests Added (FileCommandsTests.CreateEmptyThenList.cs):
- CreateEmpty_ThenOpenAndList_ReturnsSheet1
- CreateEmpty_ThenOpenAndListMultipleTimes_ConsistentResults
- CreateEmpty_ThenOpenAndCreateMoreSheets_AllSheetsVisible

All 15 file-related tests pass.

Fixes #192

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-11-17 19:37:05 +00:00
Stefan Broenner 1e996bea6d Remove file-based operations and refactor VBA to accept code strings (#191)
* Remove file-based operations and refactor VBA to accept code strings

Fixes #190

Changes:
- Removed Connection.Import and Connection.UpdateProperties (JSON file-based operations)
- Removed DataModel.ExportMeasure (DAX file export)
- Refactored VBA Import/Update to accept code strings instead of file paths
  - Core layer now accepts vbaCode string parameter
  - CLI layer handles file I/O (reads files and passes code strings)
  - MCP Server layer accepts vbaCode parameter directly
- Deleted PathValidator.cs and removed Security namespace references
- Updated all documentation (READMEs, GitHub Pages) to reflect 163 operations (down from 168)

Build status: ✅ 0 warnings, 0 errors

Breaking changes:
- VBA Import/Update signature changed in Core layer (file path → code string)
- Connection and DataModel commands removed (file-based operations)

* Fix VBA tests to pass code strings instead of file paths

The VBA command signature changed to accept code strings directly rather
than file paths. Updated all VBA trust tests to pass vbaCode strings
instead of creating temporary files and passing file paths.

Tests fixed:
- ScriptCommands_Import_WithTrustEnabled_WorksCorrectly
- ScriptCommands_Export_WithTrustEnabled_WorksCorrectly
- ScriptCommands_Run_WithTrustEnabled_WorksCorrectly
- ScriptCommands_Delete_WithTrustEnabled_WorksCorrectly
- ScriptCommands_View_WithTrustEnabled_WorksCorrectly
- ScriptCommands_Update_WithTrustEnabled_WorksCorrectly

All 7 VBA tests now pass.
2025-11-17 17:00:46 +00:00
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
Stefan Broenner efe6d6a735 Feature/session-api-redesign-spec (#185)
* Spec: redesign session API for open/save/close model

* docs: add implementation notes for session API redesign and lifecycle management

* feat: implement session API foundation

- Add SessionManager in Core layer (shared by MCP Server and CLI)
- Add WithSessionAsync helper method in ExcelToolsBase
- Implement Open/Save/Close actions in excel_file tool
- Mark WithBatchAsync as obsolete
- Document migration pattern for remaining tools

Core and ComInterop layers unchanged (IExcelBatch, batchId preserved)
MCP Server exposes sessionId to users/LLMs

* Fix double disposal race condition and Excel process leaks in SessionManager

CRITICAL FIXES:
- Fix double disposal race condition using Interlocked.CompareExchange
- Fix Excel process leaks on timeout with force-kill fallback
- Fix two-session disposal hang with sequential disposal + timeouts
- Migrate to ILogger pattern for proper test diagnostics

DISPOSAL IMPROVEMENTS:
- ExcelBatch: Atomic disposal check prevents duplicate disposal
- SessionManager: Sequential disposal with 10s timeout per session
- Excel.Quit() timeout wrapper with Task.Run + CancellationToken
- Force-kill Excel processes on timeout (Process.GetProcessesByName)

LOGGER MIGRATION:
- Replace Debug.WriteLine/Console.WriteLine with ILogger<ExcelBatch>
- Comprehensive thread ID tracking throughout disposal flow
- Proper dependency injection pattern for testability

TEST IMPROVEMENTS:
- DisposalVerificationTest: Verify Interlocked fix prevents double disposal
- SessionManagerTests: Comprehensive lifecycle and multi-session tests
- All tests pass reliably in ~18s (was timing out at 30s)
- Zero Excel process leaks verified

ARCHITECTURE:
- Move SessionManager from Core to ComInterop (correct layer)
- Remove batch-of-one pattern, use session API exclusively
- Update all MCP tools to require sessionId parameter
- Better than NetOffice: they don't handle COM deadlocks at all

AUDIT SCRIPTS:
- Add FileAction session operations to knownExceptions (Open, Save, Close)
- These are MCP-specific session management actions, not Core methods
- Update both audit-core-coverage.ps1 and check-mcp-core-implementations.ps1

Fixes #139 (double disposal bug)
Fixes #140 (Excel process leaks)
Fixes #141 (two-session hang)

* test: re-enable comprehensive smoke test for MCP tools with session API

* refactor: eliminate redundant guidance, remove obsolete batch mode, preserve critical hints

CHANGES:
- Removed 70% of redundant prompts, next-step suggestions, and elicitations
- Eliminated ALL batch mode references (API redesigned to Open/Save/Close sessions)
- Preserved only 7 critical server-specific hints (hidden sheets, #NAME? errors, connection-only detection, etc.)

DELETED FILES (12 total):
- ExcelBatchModePrompts.cs (obsolete batch mode guidance)
- excel_batch.md (obsolete tool prompt)
- 6 elicitation files (batch_workflow, dax_measure, powerquery_import, querytable_creation, range_formatting, table_creation)
- 5 redundant completion files (alignment, colors, error styles, format codes)

CLEANED TOOL FILES (11 total, 130+ methods):
- ExcelPowerQueryTool.cs - Retained 5 critical hints (Issue #170, Unload, LoadConfig, Delete side effects, Refresh timeout)
- ExcelRangeTool.cs - Removed 227 lines of guidance, retained core patterns
- ExcelTableTool.cs - Removed 126 lines of guidance, retained core patterns
- 8 remaining tool files - Cleaned batch mode references, removed generic guidance

CLEANED PROMPT FILES (12 total):
- Removed batch mode references from all 8 affected tool prompts
- Removed deleted file references from tool prompts and loaders
- Condensed tool_selection_guide.md by 80% (250→50 lines)
- Rewrote server_quirks.md and user_request_patterns.md (removed batch sections)

FIXED LOADERS:
- ExcelElicitationPrompts.cs - Removed 5 methods for deleted elicitations
- ExcelCompletionHandler.cs - Removed references to 5 deleted completion files
- ExcelScenarioPrompts.cs - Replaced all 5 batch workflows with current Open/Save/Close patterns

QUALITY METRICS:
✓ Build: 0 warnings, 0 errors
✓ All tool files clean (verified with grep)
✓ No broken references remain
✓ All guidance now server-specific only
✓ Ready for merge to main

* docs: update all documentation with correct tool/operation counts and session lifecycle

CHANGES ACROSS ALL DOCUMENTATION:
- Updated tool count: 12 → 11 specialized tools (batch mode removed)
- Updated operation count: 165 → 166 operations (new open/save/close actions)
- Replaced obsolete batch mode documentation with current session lifecycle pattern

FILES UPDATED:
- README.md (main project)
- src/ExcelMcp.McpServer/README.md (MCP Server NuGet)
- src/ExcelMcp.CLI/README.md (CLI tool documentation)
- gh-pages/index.md (GitHub Pages landing)
- vscode-extension/README.md (VS Code extension)

KEY CHANGES:
✓ CLI: Removed batch mode (batch-begin/batch-commit) - 3 obsolete commands
✓ CLI: Added session lifecycle (open/save/close) - 3 new core operations
✓ CLI: Updated command count from 150 to 166 operations
✓ CLI: Restructured category table from 13 to 11 categories
✓ All tools: Updated to reflect 11 tools, 166 operations consistently
✓ Examples: Updated batch mode examples to show open/save/close pattern

VERIFICATION:
✓ All counts match live codebase (audit script verified: 160 Core + 6 MCP-specific)
✓ Session lifecycle accurately reflects current API design
✓ Documentation consistent across all 5 locations
2025-11-14 16:13:22 +00:00
Copilot c0474b350d Add comprehensive MCP client discovery support for Claude, Cursor, Cline, and Windsurf (#175)
* Initial plan

* Add comprehensive MCP client discovery support

- Add example configs for Claude, Cursor, Cline, Windsurf, VS Code
- Update README with MCP Registry badge and multi-client setup
- Expand INSTALLATION.md with detailed per-client instructions
- Create examples/mcp-configs/ with ready-to-use config files
- Add setup guide covering all major MCP clients

Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sbroenne <3026464+sbroenne@users.noreply.github.com>
2025-11-13 18:34:16 +01:00
Stefan Broenner 85ca40073b Fix Issue #170: LoadTo detects existing sheets and returns clear error (#171)
LoadTo silently failed when target worksheet existed - Excel's CreateQueryTableForQuery doesn't update query load configuration when sheet exists. Now detects conflicts and returns clear error requiring explicit sheet deletion before retry. Includes 6 regression tests, fixes CLI pack --no-build error, and corrects pre-commit script path warning.
2025-11-10 17:48:05 +00:00
Stefan Broenner c9643b4979 Fix #167: Excel validation InputTitle/InputMessage not returned + dropdown list guidance (#168)
Root Cause:
- Excel COM API requires validation.ShowInput=true BEFORE setting InputTitle/InputMessage
- Otherwise Excel silently ignores these properties

Fix Applied:
- Reordered property assignments in ValidateRangeAsync (lines 67-72)
- Refactored GetValidationAsync to read properties into variables first (defensive)

Critical Discovery - List Validation Dropdowns:
- Comma-separated strings do NOT create dropdown arrows in Excel
- Only worksheet range references create actual dropdowns
- Updated documentation to guide users: write values to range first, then reference it

Documentation Updates:
- ExcelRangeTool.cs: Updated formula1 parameter description for list validation
- data_validation.md: Added step-by-step dropdown workflow with warning
- excel_range.md: Added to common mistakes list

Tests Added:
- ValidateRange_WithInputMessage_ReturnsSuccess: End-to-end validation workflow
- GetValidation_WithInputMessage_ReturnsInputTitleAndMessage: InputTitle/InputMessage verification
- Both tests use proper dropdown syntax (worksheet range reference)
- Tests pass (15s total, 0 warnings)

User Impact:
- InputTitle and InputMessage now work correctly
- Clear guidance on creating proper dropdown lists
- Prevents confusion about comma-separated vs range-based validation
2025-11-10 14:54:49 +00:00
Stefan Broenner 8665b97ee3 fix: VS Code extension build - move XML cleanup to after Publish (#166)
Fixes MSB3030 error in GitHub Actions by changing MSBuild target timing from AfterTargets="Build" to AfterTargets="Publish". XML files are now deleted after publish completes instead of before, preventing "file not found" errors during the publish copy phase.
2025-11-10 11:21:27 +00:00