Skip to content

Commit f4d0bd8

Browse files
session pooling pylint fixes
Signed-off-by: Mohan Lakshmaiah <mohalaks@in.ibm.com>
1 parent ebeba2e commit f4d0bd8

File tree

6 files changed

+21
-29
lines changed

6 files changed

+21
-29
lines changed

mcpgateway/cache/session_pool.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import asyncio
1111
import time
1212
import logging
13-
from typing import Dict, Optional, List, Any
13+
from typing import Dict, Optional, Any
1414
from enum import Enum
1515
from dataclasses import dataclass
1616
from mcpgateway.cache.session_registry import SessionRegistry
@@ -22,11 +22,13 @@
2222

2323
logger = logging.getLogger(__name__)
2424

25+
2526
class TransportType(Enum):
2627
"""Enumeration of supported transport types."""
2728
SSE = "sse"
2829
WEBSOCKET = "websocket"
2930

31+
3032
@dataclass
3133
class PoolKey:
3234
"""Structured key for session pooling with proper hashing."""
@@ -45,6 +47,7 @@ def __eq__(self, other):
4547
self.server_id == other.server_id and
4648
self.transport_type == other.transport_type)
4749

50+
4851
class PooledSession:
4952
"""Wrapper around transport for pooling and metrics tracking."""
5053
def __init__(self, transport: Transport, user_id: str, server_id: str, transport_type: TransportType):
@@ -118,14 +121,14 @@ def __init__(self, session_registry: SessionRegistry):
118121
if settings.session_pooling_enabled:
119122
self._start_cleanup_task()
120123
logger.info("Session pool initialized with cleanup interval=%s sec",
121-
settings.session_pool_cleanup_interval)
124+
settings.session_pool_cleanup_interval)
122125

123126
# --------------------------------------------------------------------------
124127
# Core pooling logic with multi-transport support
125128
# --------------------------------------------------------------------------
126129

127130
async def get_or_create_session(self, user_id: str, server_id: str, base_url: str,
128-
transport_type: TransportType) -> Transport:
131+
transport_type: TransportType) -> Transport:
129132
"""Get an existing session for (user, server, transport) or create a new one."""
130133
if not settings.session_pooling_enabled:
131134
logger.debug("Session pooling disabled, creating fresh session.")
@@ -160,7 +163,7 @@ async def get_or_create_session(self, user_id: str, server_id: str, base_url: st
160163
return new_session.transport
161164

162165
async def _create_new_session(self, user_id: str, server_id: str, base_url: str,
163-
transport_type: TransportType) -> PooledSession:
166+
transport_type: TransportType) -> PooledSession:
164167
"""Create and register a brand new transport session."""
165168
try:
166169
# Create transport instance based on type
@@ -185,7 +188,10 @@ async def _create_new_session(self, user_id: str, server_id: str, base_url: str,
185188
self._metrics["created"] += 1
186189

187190
logger.info("Created new %s session for user=%s server=%s (session_id=%s)",
188-
transport_type.value, user_id, server_id, transport.session_id)
191+
transport_type.value,
192+
user_id,
193+
server_id,
194+
transport.session_id)
189195
return session
190196

191197
except Exception as e:
@@ -210,14 +216,14 @@ async def _is_session_valid(self, session: PooledSession) -> bool:
210216

211217
if session.idle_time > settings.session_pool_max_idle_time:
212218
logger.debug("Session %s idle too long (idle_time=%s).",
213-
session.transport.session_id, session.idle_time)
219+
session.transport.session_id, session.idle_time)
214220
return False
215221

216222
# Additional transport-specific validation
217223
if hasattr(session.transport, 'validate_session'):
218224
if not await session.transport.validate_session():
219225
logger.debug("Session %s failed transport-specific validation.",
220-
session.transport.session_id)
226+
session.transport.session_id)
221227
return False
222228

223229
return True
@@ -331,7 +337,7 @@ def _start_cleanup_task(self):
331337
if not self._cleanup_task or self._cleanup_task.done():
332338
self._cleanup_task = asyncio.create_task(self.cleanup_expired_sessions())
333339
logger.info("Session cleanup task started (interval=%s).",
334-
settings.session_pool_cleanup_interval)
340+
settings.session_pool_cleanup_interval)
335341

336342
async def shutdown(self):
337343
"""Gracefully stop the session pool and cleanup task."""
@@ -349,4 +355,4 @@ async def shutdown(self):
349355
await self._cleanup_session(pool_key, session)
350356
self._pool.clear()
351357

352-
logger.info("Session pool shut down. Final metrics: %s", self._metrics)
358+
logger.info("Session pool shut down. Final metrics: %s", self._metrics)

mcpgateway/cache/session_registry.py

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1567,6 +1567,7 @@ async def generate_response(self, message: Dict[str, Any], transport: SSETranspo
15671567
# ------------------------------
15681568
# Observability
15691569
# ------------------------------
1570+
15701571
def get_metrics(self) -> Dict[str, int]:
15711572
"""
15721573
Retrieve internal metrics counters for the session registry.
@@ -1577,19 +1578,3 @@ def get_metrics(self) -> Dict[str, int]:
15771578
values are their current counts (int).
15781579
"""
15791580
return dict(self._metrics)
1580-
1581-
def get_session_sync(self, session_id: str) -> Optional[SSETransport]:
1582-
"""
1583-
Get session transport synchronously from local cache only.
1584-
1585-
This is a non-blocking method that only checks the local cache,
1586-
not the distributed backend. Use this when you need quick access
1587-
and know the session should be local.
1588-
1589-
Args:
1590-
session_id: Session identifier to look up.
1591-
1592-
Returns:
1593-
SSETransport object if found in local cache, None otherwise.
1594-
"""
1595-
return self._sessions.get(session_id)

mcpgateway/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@
6363
import jq
6464
from jsonpath_ng.ext import parse
6565
from jsonpath_ng.jsonpath import JSONPath
66-
from pydantic import Field, field_validator, HttpUrl, model_validator, PositiveInt, SecretStr, BaseModel
66+
from pydantic import Field, field_validator, HttpUrl, model_validator, PositiveInt, SecretStr
6767
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
6868

6969
# Only configure basic logging if no handlers exist yet

mcpgateway/services/server_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1221,7 +1221,7 @@ async def should_use_pooling(self, db: Session, server_id: str) -> bool:
12211221
True
12221222
"""
12231223
strategy = await self.get_session_strategy(db, server_id)
1224-
return strategy in ["user-server", "global", "enabled"] # Handle potential naming variations like "user_server"
1224+
return strategy in ["user-server", "global", "enabled"] # Handle potential naming variations like "user_server"
12251225

12261226
# --- Metrics ---
12271227
async def aggregate_metrics(self, db: Session) -> ServerMetrics:

mcpgateway/transports/base.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,6 @@ async def is_connected(self) -> bool:
137137

138138
async def validate_session(self) -> bool:
139139
"""Validate session is still usable."""
140-
return await self.is_connected()
140+
return await self.is_connected()
141+
142+

mcpgateway/transports/sse_transport.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from datetime import datetime
1515
import json
1616
from typing import Any, AsyncGenerator, Dict
17-
import uuid
1817
import time
1918

2019
# Third-Party

0 commit comments

Comments
 (0)