Skip to content

Commit c51782c

Browse files
committed
lifespan for graceful entry and exit of mcp server
1 parent 07e2243 commit c51782c

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

myserver.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,43 @@
1-
from fastmcp import FastMCP
1+
from contextlib import asynccontextmanager
22
from pathlib import Path
33

4+
from fastmcp import FastMCP
5+
46
from tests.scripts.end_to_end_test_utilities import TestConfig, run_codeflash_command
57

8+
9+
# Define lifespan context manager
10+
@asynccontextmanager
11+
async def lifespan(mcp: FastMCP) -> None:
12+
print("Starting up...")
13+
print(mcp.name)
14+
# Do startup work here (connect to DB, initialize cache, etc.)
15+
yield
16+
# Cleanup work after shutdown
17+
print("Shutting down...")
18+
19+
620
mcp = FastMCP(
721
name="codeflash",
822
instructions="""
923
This server provides code optimization tools.
1024
Call optimize_code(file, function) to optimize your code.
1125
""",
26+
lifespan=lifespan,
1227
)
1328

1429

1530
@mcp.tool
1631
def optimize_code(file: str, function: str) -> str:
1732
# TODO ask for pr or no pr if successful
18-
config = TestConfig(
19-
file_path=Path(f"{file}"),
20-
function_name=f"{function}",
21-
test_framework="pytest",
22-
)
33+
config = TestConfig(file_path=Path(f"{file}"), function_name=f"{function}", test_framework="pytest")
2334
cwd = Path(file).resolve().parent
2435
status = run_codeflash_command(cwd, config, expected_improvement_pct=5)
2536
if status:
2637
return "Optimization Successful, file has been edited"
27-
else:
28-
return "Codeflash run did not meet expected requirements for testing, reverting file changes."
38+
return "Codeflash run did not meet expected requirements for testing, reverting file changes."
2939

3040

3141
if __name__ == "__main__":
3242
mcp.run(transport="stdio")
33-
# Optimize my codebase, the file is "/Users/codeflash/Downloads/codeflash-dev/codeflash/code_to_optimize/bubble_sort.py" and the function is "sorter"
43+
# Optimize my codebase, the file is "/Users/codeflash/Downloads/codeflash-dev/codeflash/code_to_optimize/bubble_sort.py" and the function is "sorter"

0 commit comments

Comments
 (0)