Skip to content

Commit a9b7bf6

Browse files
committed
Add lifespan to FastAPI app
1 parent 0c15017 commit a9b7bf6

File tree

2 files changed

+60
-55
lines changed

2 files changed

+60
-55
lines changed

mcpgateway/main.py

Lines changed: 58 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,70 @@
157157
# Initialize cache
158158
resource_cache = ResourceCache(max_size=settings.resource_cache_size, ttl=settings.resource_cache_ttl)
159159

160+
161+
####################
162+
# Startup/Shutdown #
163+
####################
164+
@asynccontextmanager
165+
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
166+
"""
167+
Manage the application's startup and shutdown lifecycle.
168+
169+
The function initialises every core service on entry and then
170+
shuts them down in reverse order on exit.
171+
172+
Args:
173+
app (FastAPI): FastAPI app
174+
175+
Yields:
176+
None
177+
178+
Raises:
179+
Exception: Any unhandled error that occurs during service
180+
initialisation or shutdown is re-raised to the caller.
181+
"""
182+
logger.info("Starting MCP Gateway services")
183+
try:
184+
await tool_service.initialize()
185+
await resource_service.initialize()
186+
await prompt_service.initialize()
187+
await gateway_service.initialize()
188+
await root_service.initialize()
189+
await completion_service.initialize()
190+
await logging_service.initialize()
191+
await sampling_handler.initialize()
192+
await resource_cache.initialize()
193+
logger.info("All services initialized successfully")
194+
yield
195+
except Exception as e:
196+
logger.error(f"Error during startup: {str(e)}")
197+
raise
198+
finally:
199+
logger.info("Shutting down MCP Gateway services")
200+
for service in [
201+
resource_cache,
202+
sampling_handler,
203+
logging_service,
204+
completion_service,
205+
root_service,
206+
gateway_service,
207+
prompt_service,
208+
resource_service,
209+
tool_service,
210+
]:
211+
try:
212+
await service.shutdown()
213+
except Exception as e:
214+
logger.error(f"Error shutting down {service.__class__.__name__}: {str(e)}")
215+
logger.info("Shutdown complete")
216+
160217
# Initialize FastAPI app
161218
app = FastAPI(
162219
title=settings.app_name,
163220
version=__version__,
164221
description="A FastAPI-based MCP Gateway with federation support",
165222
root_path=settings.app_root_path,
223+
lifespan=lifespan,
166224
)
167225

168226

@@ -1909,60 +1967,6 @@ async def healthcheck(db: Session = Depends(get_db)):
19091967
return {"status": "healthy"}
19101968

19111969

1912-
####################
1913-
# Startup/Shutdown #
1914-
####################
1915-
@asynccontextmanager
1916-
async def lifespan() -> AsyncIterator[None]:
1917-
"""
1918-
Manage the application's startup and shutdown lifecycle.
1919-
1920-
The function initialises every core service on entry and then
1921-
shuts them down in reverse order on exit.
1922-
1923-
Yields:
1924-
None
1925-
1926-
Raises:
1927-
Exception: Any unhandled error that occurs during service
1928-
initialisation or shutdown is re-raised to the caller.
1929-
"""
1930-
logger.info("Starting MCP Gateway services")
1931-
try:
1932-
await tool_service.initialize()
1933-
await resource_service.initialize()
1934-
await prompt_service.initialize()
1935-
await gateway_service.initialize()
1936-
await root_service.initialize()
1937-
await completion_service.initialize()
1938-
await logging_service.initialize()
1939-
await sampling_handler.initialize()
1940-
await resource_cache.initialize()
1941-
logger.info("All services initialized successfully")
1942-
yield
1943-
except Exception as e:
1944-
logger.error(f"Error during startup: {str(e)}")
1945-
raise
1946-
finally:
1947-
logger.info("Shutting down MCP Gateway services")
1948-
for service in [
1949-
resource_cache,
1950-
sampling_handler,
1951-
logging_service,
1952-
completion_service,
1953-
root_service,
1954-
gateway_service,
1955-
prompt_service,
1956-
resource_service,
1957-
tool_service,
1958-
]:
1959-
try:
1960-
await service.shutdown()
1961-
except Exception as e:
1962-
logger.error(f"Error shutting down {service.__class__.__name__}: {str(e)}")
1963-
logger.info("Shutdown complete")
1964-
1965-
19661970
# Mount static files
19671971
app.mount("/static", StaticFiles(directory=str(settings.static_dir)), name="static")
19681972

mcpgateway/services/gateway_service.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from mcpgateway.config import settings
3030
from mcpgateway.db import Gateway as DbGateway
3131
from mcpgateway.db import Tool as DbTool
32+
from mcpgateway.db import SessionLocal
3233
from mcpgateway.schemas import GatewayCreate, GatewayRead, GatewayUpdate, ToolCreate
3334
from mcpgateway.services.tool_service import ToolService
3435
from mcpgateway.utils.services_auth import decode_auth
@@ -579,7 +580,7 @@ async def connect_to_sse_server(server_url: str, authentication: Optional[Dict[s
579580

580581
def _get_active_gateways(self) -> list[DbGateway]:
581582
"""Sync function for database operations (runs in thread)."""
582-
with Session() as db:
583+
with SessionLocal() as db:
583584
return db.execute(select(DbGateway).where(DbGateway.is_active)).scalars().all()
584585

585586
async def _run_health_checks(self) -> None:

0 commit comments

Comments
 (0)