Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbbab5bf

Browse files
authored
Feat/add stdio transport (#25)
* feat: Add stdio transport method.Update relevant documentation and code to support both SSE and stdio connection methods, initialize the EXCEL_FILES_PATH variable and perform the corresponding path handling.* Remove PyPI mirror configuration.
1 parent46adf0b commitbbab5bf

File tree

4 files changed

+131
-54
lines changed

4 files changed

+131
-54
lines changed

‎README.md

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ A Model Context Protocol (MCP) server that lets you manipulate Excel files witho
1212
- 📈 Create charts and visualizations
1313
- 📊 Generate pivot tables
1414
- 🔄 Manage worksheets and ranges
15+
- 🔌 Dual transport support: stdio and SSE
1516

1617
##Quick Start
1718

@@ -34,54 +35,77 @@ uv pip install -e .
3435

3536
###Running the Server
3637

37-
Start the server (default port 8000):
38+
The server supports two transport modes: stdio and SSE.
39+
40+
####Using stdio transport (default)
41+
42+
Stdio transport is ideal for direct integration with tools like Cursor Desktop or local development, which can manipulate local files:
43+
3844
```bash
39-
uv runexcel-mcp-server
45+
excel-mcp-server stdio
4046
```
4147

42-
Custom port (e.g., 8080):
48+
####Using SSE transport
49+
50+
SSE transport is perfect for web-based applications and remote connections, which manipulate remote files:
4351

4452
```bash
45-
# Bash/Linux/macOS
46-
export FASTMCP_PORT=8080&& uv run excel-mcp-server
53+
excel-mcp sse
54+
```
55+
56+
You can specify host and port for the SSE server:
4757

48-
# Windows PowerShell
49-
$env:FASTMCP_PORT ="8080"; uv run excel-mcp-server
58+
```bash
59+
excel-mcp sse --host 127.0.0.1 --port 8080
5060
```
5161

5262
##Using with AI Tools
5363

5464
###Cursor IDE
5565

56-
1. Add this configuration to Cursor:
66+
1. Add this configuration to Cursor, choosing the appropriate transport method for your needs:
67+
68+
**Stdio transport connection** (for local integration):
69+
```json
70+
{
71+
"mcpServers": {
72+
"excel-stdio": {
73+
"command":"uv",
74+
"args": ["run","excel-mcp-server","stdio"]
75+
}
76+
}
77+
}
78+
```
79+
80+
**SSE transport connection** (for web-based applications):
5781
```json
5882
{
59-
"mcpServers": {
60-
"excel": {
61-
"url":"http://localhost:8000/sse",
62-
"env": {
63-
"EXCEL_FILES_PATH":"/path/to/excel/files"
83+
"mcpServers": {
84+
"excel": {
85+
"url":"http://localhost:8000/sse",
86+
"env": {
87+
"EXCEL_FILES_PATH":"/path/to/excel/files"
88+
}
6489
}
65-
}
66-
}
90+
}
6791
}
6892
```
6993

7094
2. The Excel tools will be available through your AI assistant.
7195

7296
###Remote Hosting & Transport Protocols
7397

74-
This serveruses Server-Sent Events (SSE) transportprotocol. For different use cases:
98+
This serversupports both stdio andSSE transportprotocols for maximum flexibility:
7599

76-
1.**Using with Claude Desktop (requires stdio):**
77-
- Use[Supergateway](https://github.com/supercorp-ai/supergateway) to convert SSE to stdio:
100+
1.**Using with Claude Desktop:**
101+
- UseStdio transport
78102

79-
2.**Hosting Your MCP Server:**
103+
2.**Hosting Your MCP Server (SSE):**
80104
-[Remote MCP Server Guide](https://developers.cloudflare.com/agents/guides/remote-mcp-server/)
81105

82-
##Environment Variables
106+
##Environment Variables (for SSE transport)
83107

84-
-`FASTMCP_PORT`: Server port (default: 8000)
108+
-`FASTMCP_PORT`: Server portfor SSE transport(default: 8000)
85109
-`EXCEL_FILES_PATH`: Directory for Excel files (default:`./excel_files`)
86110

87111
##Available Tools

‎pyproject.toml

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
11
[project]
22
name ="excel-mcp-server"
33
version ="0.1.1"
4-
description ="MCPserver for Excelfile manipulation"
4+
description ="ExcelMCPServer formanipulatingExcelfiles"
55
readme ="README.md"
66
requires-python =">=3.10"
77
dependencies = [
8-
"mcp[cli]>=1.2.0",
9-
"openpyxl>=3.1.2"
8+
"mcp[cli]>=1.6.0",
9+
"openpyxl>=3.1.2",
10+
"typer>=0.15.1"
1011
]
1112
[[project.authors]]
1213
name ="haris"
1314
email ="haris.musa@outlook.com"
1415

16+
[project.scripts]
17+
excel-mcp-server ="excel_mcp.__main__:app"
18+
1519
[build-system]
1620
requires = ["hatchling"]
1721
build-backend ="hatchling.build"
1822

19-
[project.scripts]
20-
excel-mcp-server ="excel_mcp.__main__:main"
21-
2223
[tool.hatch.build.targets.wheel]
2324
packages = ["src/excel_mcp"]
2425

2526
[tool.hatch.build]
26-
packages = ["src/excel_mcp"]
27+
packages = ["src/excel_mcp"]

‎src/excel_mcp/__main__.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,41 @@
11
importasyncio
2-
from .serverimportrun_server
2+
importtyper
3+
fromtypingimportOptional
34

4-
defmain():
5-
"""Start the Excel MCP server."""
5+
from .serverimportrun_sse,run_stdio
6+
7+
app=typer.Typer(help="Excel MCP Server")
8+
9+
@app.command()
10+
defsse():
11+
"""Start Excel MCP Server in SSE mode"""
12+
print("Excel MCP Server - SSE mode")
13+
print("----------------------")
14+
print("Press Ctrl+C to exit")
15+
try:
16+
asyncio.run(run_sse())
17+
exceptKeyboardInterrupt:
18+
print("\nShutting down server...")
19+
exceptExceptionase:
20+
print(f"\nError:{e}")
21+
importtraceback
22+
traceback.print_exc()
23+
finally:
24+
print("Service stopped.")
25+
26+
@app.command()
27+
defstdio():
28+
"""Start Excel MCP Server in stdio mode"""
629
try:
7-
print("Excel MCP Server")
8-
print("---------------")
9-
print("Starting server... Press Ctrl+C to exit")
10-
asyncio.run(run_server())
30+
run_stdio()
1131
exceptKeyboardInterrupt:
1232
print("\nShutting down server...")
1333
exceptExceptionase:
1434
print(f"\nError:{e}")
1535
importtraceback
1636
traceback.print_exc()
1737
finally:
18-
print("Server stopped.")
38+
print("Service stopped.")
1939

2040
if__name__=="__main__":
21-
main()
41+
app()

‎src/excel_mcp/server.py

Lines changed: 49 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,25 +34,31 @@
3434
unmerge_range,
3535
)
3636

37+
# Get project root directory path for log file path.
38+
# When using the stdio transmission method,
39+
# relative paths may cause log files to fail to create
40+
# due to the client's running location and permission issues,
41+
# resulting in the program not being able to run.
42+
# Thus using os.path.join(ROOT_DIR, "excel-mcp.log") instead.
43+
44+
ROOT_DIR=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
45+
LOG_FILE=os.path.join(ROOT_DIR,"excel-mcp.log")
46+
47+
48+
# Initialize EXCEL_FILES_PATH variable without assigning a value
49+
EXCEL_FILES_PATH=None
50+
3751
# Configure logging
3852
logging.basicConfig(
3953
level=logging.INFO,
4054
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
4155
handlers=[
42-
logging.StreamHandler(sys.stdout),
43-
logging.FileHandler("excel-mcp.log")
56+
# Referring to https://github.com/modelcontextprotocol/python-sdk/issues/409#issuecomment-2816831318
57+
# The stdio mode server MUST NOT write anything to its stdout that is not a valid MCP message.
58+
logging.FileHandler(LOG_FILE)
4459
],
45-
force=True
4660
)
47-
4861
logger=logging.getLogger("excel-mcp")
49-
50-
# Get Excel files path from environment or use default
51-
EXCEL_FILES_PATH=os.environ.get("EXCEL_FILES_PATH","./excel_files")
52-
53-
# Create the directory if it doesn't exist
54-
os.makedirs(EXCEL_FILES_PATH,exist_ok=True)
55-
5662
# Initialize FastMCP server
5763
mcp=FastMCP(
5864
"excel-mcp",
@@ -80,8 +86,13 @@ def get_excel_path(filename: str) -> str:
8086
# If filename is already an absolute path, return it
8187
ifos.path.isabs(filename):
8288
returnfilename
83-
84-
# Use the configured Excel files path
89+
90+
# Check if in SSE mode (EXCEL_FILES_PATH is not None)
91+
ifEXCEL_FILES_PATHisNone:
92+
# Must use absolute path
93+
raiseValueError(f"Invalid filename:{filename}, must be an absolute path when not in SSE mode")
94+
95+
# In SSE mode, if it's a relative path, resolve it based on EXCEL_FILES_PATH
8596
returnos.path.join(EXCEL_FILES_PATH,filename)
8697

8798
@mcp.tool()
@@ -491,10 +502,16 @@ def validate_excel_range(
491502
logger.error(f"Error validating range:{e}")
492503
raise
493504

494-
asyncdefrun_server():
495-
"""Run the Excel MCP server."""
505+
asyncdefrun_sse():
506+
"""Run Excel MCP server in SSE mode."""
507+
# Assign value to EXCEL_FILES_PATH in SSE mode
508+
globalEXCEL_FILES_PATH
509+
EXCEL_FILES_PATH=os.environ.get("EXCEL_FILES_PATH","./excel_files")
510+
# Create directory if it doesn't exist
511+
os.makedirs(EXCEL_FILES_PATH,exist_ok=True)
512+
496513
try:
497-
logger.info(f"Starting Excel MCP server (files directory:{EXCEL_FILES_PATH})")
514+
logger.info(f"Starting Excel MCP serverwith SSE transport(files directory:{EXCEL_FILES_PATH})")
498515
awaitmcp.run_sse_async()
499516
exceptKeyboardInterrupt:
500517
logger.info("Server stopped by user")
@@ -503,4 +520,19 @@ async def run_server():
503520
logger.error(f"Server failed:{e}")
504521
raise
505522
finally:
506-
logger.info("Server shutdown complete")
523+
logger.info("Server shutdown complete")
524+
525+
defrun_stdio():
526+
"""Run Excel MCP server in stdio mode."""
527+
# No need to assign EXCEL_FILES_PATH in stdio mode
528+
529+
try:
530+
logger.info("Starting Excel MCP server with stdio transport")
531+
mcp.run(transport="stdio")
532+
exceptKeyboardInterrupt:
533+
logger.info("Server stopped by user")
534+
exceptExceptionase:
535+
logger.error(f"Server failed:{e}")
536+
raise
537+
finally:
538+
logger.info("Server shutdown complete")

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp