mcp-win-stdio-excel 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """
2
+ mcp-win-stdio-excel: Windows-optimized Excel MCP Server.
3
+ """
4
+
5
+ __version__ = "0.2.3"
@@ -0,0 +1,8 @@
1
+ """
2
+ Direct module execution for mcp_win_stdio.excel.
3
+ """
4
+
5
+ from mcp_win_stdio.excel.server import mcp
6
+
7
+ if __name__ == "__main__":
8
+ mcp.run()
@@ -0,0 +1,186 @@
1
+ """
2
+ CLI entry point for mcp-win-stdio-excel.
3
+ """
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+
13
+ from mcp_win_stdio.excel import __version__
14
+ from mcp_win_stdio.excel.guide import print_guide
15
+ from mcp_win_stdio.excel.server import mcp
16
+
17
+
18
+ def get_claude_desktop_config_path() -> Path | None:
19
+ appdata = os.environ.get("APPDATA")
20
+ if appdata:
21
+ p = Path(appdata) / "Claude" / "claude_desktop_config.json"
22
+ if p.exists():
23
+ return p
24
+ default_p = Path.home() / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json"
25
+ return default_p if default_p.exists() else None
26
+
27
+
28
+ def get_claude_cli_config_path() -> Path | None:
29
+ p = Path.home() / ".claude.json"
30
+ return p if p.exists() else None
31
+
32
+
33
+ def cmd_setup(args: argparse.Namespace) -> None:
34
+ """Setup excel MCP server in Claude Desktop and Claude Code CLI."""
35
+ client = args.client.lower()
36
+ python_exe = sys.executable.replace("\\", "/")
37
+ cmd_args = ["-m", "mcp_win_stdio.excel.server"]
38
+
39
+ print(f"\nSetting up 'excel' MCP server (target: {client})...\n")
40
+
41
+ # 1. Desktop
42
+ if client in ("all", "desktop"):
43
+ desktop_cfg = get_claude_desktop_config_path()
44
+ if desktop_cfg:
45
+ try:
46
+ shutil.copy2(desktop_cfg, desktop_cfg.with_suffix(".json.bak"))
47
+ with open(desktop_cfg, "r", encoding="utf-8") as f:
48
+ data = json.load(f)
49
+ if "mcpServers" not in data:
50
+ data["mcpServers"] = {}
51
+ data["mcpServers"]["excel"] = {
52
+ "command": python_exe,
53
+ "args": cmd_args,
54
+ }
55
+ with open(desktop_cfg, "w", encoding="utf-8") as f:
56
+ json.dump(data, f, indent=2)
57
+ print(f"[OK] Claude Desktop: Configured 'excel' in {desktop_cfg}")
58
+ except Exception as e:
59
+ print(f"[ERROR] Claude Desktop: Failed to configure: {e}")
60
+ else:
61
+ print("[WARN] Claude Desktop configuration not found.")
62
+
63
+ # 2. CLI
64
+ if client in ("all", "cli"):
65
+ added_cli = False
66
+ try:
67
+ res = subprocess.run(
68
+ ["claude", "mcp", "add", "-s", "user", "excel", "--", python_exe] + cmd_args,
69
+ capture_output=True,
70
+ text=True,
71
+ timeout=10,
72
+ )
73
+ if res.returncode == 0:
74
+ added_cli = True
75
+ print("[OK] Claude Code CLI: Configured via `claude mcp add`")
76
+ except Exception:
77
+ pass
78
+
79
+ if not added_cli:
80
+ cli_cfg = get_claude_cli_config_path()
81
+ if cli_cfg:
82
+ try:
83
+ with open(cli_cfg, "r", encoding="utf-8") as f:
84
+ cli_data = json.load(f)
85
+ if "mcpServers" not in cli_data:
86
+ cli_data["mcpServers"] = {}
87
+ cli_data["mcpServers"]["excel"] = {
88
+ "command": python_exe,
89
+ "args": cmd_args,
90
+ }
91
+ with open(cli_cfg, "w", encoding="utf-8") as f:
92
+ json.dump(cli_data, f, indent=2)
93
+ print(f"[OK] Claude Code CLI: Configured directly in {cli_cfg}")
94
+ except Exception as e:
95
+ print(f"[ERROR] Claude CLI: Failed to configure: {e}")
96
+
97
+ print("\nExcel MCP setup complete! Please restart Claude Desktop if active.\n")
98
+
99
+
100
+ def cmd_remove(args: argparse.Namespace) -> None:
101
+ """Remove excel MCP server from Claude Desktop and CLI."""
102
+ desktop_cfg = get_claude_desktop_config_path()
103
+ if desktop_cfg and desktop_cfg.exists():
104
+ try:
105
+ with open(desktop_cfg, "r", encoding="utf-8") as f:
106
+ data = json.load(f)
107
+ if "mcpServers" in data and "excel" in data["mcpServers"]:
108
+ del data["mcpServers"]["excel"]
109
+ with open(desktop_cfg, "w", encoding="utf-8") as f:
110
+ json.dump(data, f, indent=2)
111
+ print(f"[OK] Removed 'excel' from Claude Desktop.")
112
+ except Exception as e:
113
+ print(f"[ERROR] Claude Desktop: {e}")
114
+
115
+ try:
116
+ res = subprocess.run(["claude", "mcp", "remove", "-s", "user", "excel"], capture_output=True, text=True)
117
+ if res.returncode == 0:
118
+ print("[OK] Removed 'excel' from Claude Code CLI.")
119
+ except Exception:
120
+ pass
121
+
122
+
123
+ def cmd_run(args: argparse.Namespace) -> None:
124
+ """Run excel MCP server over stdio."""
125
+ mcp.run()
126
+
127
+
128
+ def cmd_doctor(args: argparse.Namespace) -> None:
129
+ """Check Excel MCP health and dependencies."""
130
+ print(f"\n=== mcp-win-stdio-excel Doctor Diagnostic (v{__version__}) ===\n")
131
+ print(f"[OK] Python: {sys.version.split()[0]} ({sys.executable})")
132
+
133
+ for dep in ("mcp", "pandas", "openpyxl", "rapidfuzz", "win32com"):
134
+ try:
135
+ __import__(dep)
136
+ print(f"[OK] Dependency: {dep:<12}")
137
+ except ImportError:
138
+ print(f"[FAIL] Dependency: {dep:<12} (MISSING)")
139
+
140
+ print("\n--- Excel COM Automation Check ---")
141
+ try:
142
+ import win32com.client
143
+ app = win32com.client.DispatchEx("Excel.Application")
144
+ ver = app.Version
145
+ app.Quit()
146
+ print(f"[OK] Microsoft Excel COM: Available (Version {ver})")
147
+ except Exception as e:
148
+ print(f"[INFO] Microsoft Excel COM: Not detected ({e})")
149
+
150
+ print("\nDiagnostic complete.\n")
151
+
152
+
153
+ def main() -> None:
154
+ parser = argparse.ArgumentParser(
155
+ prog="mcp-win-stdio-excel",
156
+ description="Windows-optimized Excel MCP Server CLI",
157
+ )
158
+ parser.add_argument("--version", "-v", action="version", version=f"%(prog)s {__version__}")
159
+ subparsers = parser.add_subparsers(dest="command", help="Command to execute")
160
+
161
+ sub_setup = subparsers.add_parser("setup", help="Auto-configure into Claude Desktop & CLI")
162
+ sub_setup.add_argument("--client", "-c", choices=["all", "desktop", "cli"], default="all")
163
+ sub_setup.set_defaults(func=cmd_setup)
164
+
165
+ sub_remove = subparsers.add_parser("remove", help="Remove from Claude Desktop & CLI")
166
+ sub_remove.set_defaults(func=cmd_remove)
167
+
168
+ sub_guide = subparsers.add_parser("guide", help="View usage guide and prompt recipes")
169
+ sub_guide.set_defaults(func=lambda args: print_guide())
170
+
171
+ sub_run = subparsers.add_parser("run", help="Run Excel MCP server over stdio")
172
+ sub_run.set_defaults(func=cmd_run)
173
+
174
+ sub_doctor = subparsers.add_parser("doctor", help="Check dependencies and COM automation")
175
+ sub_doctor.set_defaults(func=cmd_doctor)
176
+
177
+ args = parser.parse_args()
178
+ if not args.command:
179
+ parser.print_help()
180
+ sys.exit(0)
181
+
182
+ args.func(args)
183
+
184
+
185
+ if __name__ == "__main__":
186
+ main()
@@ -0,0 +1,69 @@
1
+ """
2
+ Interactive and printable guide for the Excel MCP server.
3
+ """
4
+
5
+ EXCEL_GUIDE = """
6
+ # ================================================================
7
+ # EXCEL MCP (WINDOWS NATIVE + PANDAS) - USER & LLM GUIDE
8
+ # ================================================================
9
+
10
+ The Excel MCP server provides 20 specialized tools for programmatic
11
+ reading, updating, querying, fuzzy reconciling, and automating Excel
12
+ workbooks on Windows.
13
+
14
+ ----------------------------------------------------------------
15
+ 1. TOOL SUMMARY
16
+ ----------------------------------------------------------------
17
+ * Read & Inspect:
18
+ - get_workbook_info(file_path): Sheet names, dimensions, cell counts.
19
+ - preview_sheet(file_path, sheet_name, max_rows): Fast preview.
20
+ - query_rows(file_path, sheet_name, query_expr, columns): Pandas query.
21
+ - read_range(file_path, sheet_name, range_address): Slices (e.g. A1:D50).
22
+ - summarize_column(file_path, sheet_name, column_name): Statistics.
23
+ - search_text(file_path, sheet_name, search_term): Keyword search.
24
+
25
+ * Edit & Manage:
26
+ - create_workbook(file_path, sheet_name, headers, initial_rows): Create xlsx.
27
+ - append_rows(file_path, sheet_name, rows): In-place fast row append.
28
+ - update_cells(file_path, sheet_name, updates): Set values & formulas.
29
+ - add_sheet(file_path, sheet_name, title): Add new worksheet.
30
+ - rename_sheet(file_path, old_name, new_name): Rename worksheet.
31
+ - delete_sheet(file_path, sheet_name): Delete worksheet.
32
+ - export_to_csv(file_path, sheet_name, output_csv_path): CSV export.
33
+
34
+ * Reconciliation & Audit:
35
+ - analyze_reconciliation_keys(wb1, s1, keys1, wb2, s2, keys2):
36
+ PRE-FLIGHT analysis. Checks nulls, duplicate keys, overlap %, and
37
+ candidate fuzzy matches before any merging is performed!
38
+ - reconcile_and_merge(wb1, s1, keys1, wb2, s2, keys2, output_wb, fuzzy_matching=True):
39
+ Generates an automated 3-tab audit workbook:
40
+ [1] Matched (exact + fuzzy with confidence scores & variance)
41
+ [2] Unmatched_Source_1
42
+ [3] Unmatched_Source_2
43
+
44
+ * Native Windows Excel COM Automation (Requires installed Excel):
45
+ - recalculate_and_save(file_path): Forces formula engine calculation.
46
+ - export_to_pdf(file_path, output_pdf_path): Native high-res PDF export.
47
+ - refresh_data_and_pivots(file_path): Refreshes PowerQuery / Pivot tables.
48
+ - run_vba_macro(file_path, macro_name): Executes workbook VBA macros.
49
+ - get_active_excel_window(): Inspects open Excel instances.
50
+
51
+ ----------------------------------------------------------------
52
+ 2. EXAMPLE PROMPTS FOR CLAUDE
53
+ ----------------------------------------------------------------
54
+ * Pre-flight Check:
55
+ "Analyze the reconciliation keys between orders.xlsx (sheet: Sheet1,
56
+ keys: PO_Number, Vendor) and sap_report.xlsx (sheet: PR_Data,
57
+ keys: SAP_PO, Vendor_ID) and tell me match rate and fuzzy candidates."
58
+
59
+ * Reconcile:
60
+ "Reconcile those workbooks into audit_result.xlsx with fuzzy matching
61
+ enabled and show me the unmatched items."
62
+
63
+ * COM Automation:
64
+ "Recalculate formulas in audit_result.xlsx and export it to PDF."
65
+ # ================================================================
66
+ """
67
+
68
+ def print_excel_guide() -> None:
69
+ print(EXCEL_GUIDE.strip())