Skip to content

Commit 443ea94

Browse files
ChrisPC-39Sebastian
andauthored
Pylint improvements (#332)
* Pylint cli * Pylint sampling * Pylint schemas * Pyling completion_services * Pylint resource_service * Pylint streamablehttp_transport * Pylint websocket_transport * Pylint mcpgateway/admin.py * Pylint mcpgateway/federation/discovery.py * Pylint mcpgateway/federation/forward.py * Pylint mcpgateway/federation/manager.py * Pylint mcpgateway/services/prompt_service.py * Pylint mcpgateway/services/server_service.py * Pylint mcpgateway/services/tool_service.py * Pylint mcpgateway/transports/sse_transport.py * Pylint mcpgateway/version.py * Pylint mcpgateway/wrapper.py * Remove unneccessary pylint ignore comments * Load pylint-pydantic plugin in .pylintrc * Pylint mcpgateway/db.py * Pylint mcpgateway/main.py * Pylint mcpgateway/translate.py * Pylint mcpgateway/cache/session_registry.py * Pylint mcpgateway/translate.py Signed-off-by: Sebastian <[email protected]> * Pylint part of mcpgateway/services/gateway_service.py Signed-off-by: Sebastian <[email protected]> * Fix typo in mcpgateway/translate.py Signed-off-by: Sebastian <[email protected]> * Merge main and small fixes Signed-off-by: Sebastian <[email protected]> * Fix typo in mcpgateway/cache/session_registry.py Signed-off-by: Sebastian <[email protected]> * Fix flake8 Signed-off-by: Sebastian <[email protected]> --------- Signed-off-by: Sebastian <[email protected]> Co-authored-by: Sebastian <[email protected]>
1 parent c8f9a0c commit 443ea94

File tree

8 files changed

+30
-28
lines changed

8 files changed

+30
-28
lines changed

mcpgateway/bootstrap_db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
import logging
2626

2727
# Third-Party
28-
from alembic.config import Config
2928
from sqlalchemy import create_engine, inspect
3029

3130
# First-Party
3231
from alembic import command
32+
from alembic.config import Config
3333
from mcpgateway.config import settings
3434
from mcpgateway.db import Base
3535

mcpgateway/cache/session_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ def _db_cleanup():
570570
continue
571571

572572
# Refresh session in database
573-
def _refresh_session():
573+
def _refresh_session(session_id=session_id):
574574
db_session = next(get_db())
575575
try:
576576
session = db_session.query(SessionRecord).filter(SessionRecord.session_id == session_id).first()

mcpgateway/handlers/sampling.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
# First-Party
2020
from mcpgateway.models import CreateMessageResult, ModelPreferences, Role, TextContent
2121

22+
2223
logger = logging.getLogger(__name__)
2324

2425

mcpgateway/main.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -290,14 +290,14 @@ class MCPPathRewriteMiddleware:
290290
- All other requests are passed through without change.
291291
"""
292292

293-
def __init__(self, app):
293+
def __init__(self, application):
294294
"""
295295
Initialize the middleware with the ASGI application.
296296
297297
Args:
298-
app (Callable): The next ASGI application in the middleware stack.
298+
application (Callable): The next ASGI application in the middleware stack.
299299
"""
300-
self.app = app
300+
self.application = application
301301

302302
async def __call__(self, scope, receive, send):
303303
"""
@@ -310,7 +310,7 @@ async def __call__(self, scope, receive, send):
310310
"""
311311
# Only handle HTTP requests, HTTPS uses scope["type"] == "http" in ASGI
312312
if scope["type"] != "http":
313-
await self.app(scope, receive, send)
313+
await self.application(scope, receive, send)
314314
return
315315

316316
# Call auth check first
@@ -325,7 +325,7 @@ async def __call__(self, scope, receive, send):
325325
scope["path"] = "/mcp"
326326
await streamable_http_session.handle_streamable_http(scope, receive, send)
327327
return
328-
await self.app(scope, receive, send)
328+
await self.application(scope, receive, send)
329329

330330

331331
# Configure CORS

mcpgateway/services/gateway_service.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@
3232
from sqlalchemy import select
3333
from sqlalchemy.orm import Session
3434

35+
try:
36+
# Third-Party
37+
import redis
38+
39+
REDIS_AVAILABLE = True
40+
except ImportError:
41+
REDIS_AVAILABLE = False
42+
logging.info("Redis is not utilized in this environment.")
43+
3544
# First-Party
3645
from mcpgateway.config import settings
3746
from mcpgateway.db import Gateway as DbGateway
@@ -42,15 +51,6 @@
4251
from mcpgateway.utils.create_slug import slugify
4352
from mcpgateway.utils.services_auth import decode_auth
4453

45-
try:
46-
# Third-Party
47-
import redis
48-
49-
REDIS_AVAILABLE = True
50-
except ImportError:
51-
REDIS_AVAILABLE = False
52-
logging.info("Redis is not utilized in this environment.")
53-
5454
# logging.getLogger("httpx").setLevel(logging.WARNING) # Disables httpx logs for regular health checks
5555
logger = logging.getLogger(__name__)
5656

@@ -247,16 +247,16 @@ async def register_gateway(self, db: Session, gateway: GatewayCreate) -> Gateway
247247

248248
return GatewayRead.model_validate(gateway)
249249
except* GatewayConnectionError as ge:
250-
logger.error("GatewayConnectionError in group: %s", ge.exceptions)
250+
logger.error(f"GatewayConnectionError in group: {ge.exceptions}")
251251
raise ge.exceptions[0]
252252
except* ValueError as ve:
253-
logger.error("ValueErrors in group: %s", ve.exceptions)
253+
logger.error(f"ValueErrors in group: {ve.exceptions}")
254254
raise ve.exceptions[0]
255255
except* RuntimeError as re:
256-
logger.error("RuntimeErrors in group: %s", re.exceptions)
256+
logger.error(f"RuntimeErrors in group: {re.exceptions}")
257257
raise re.exceptions[0]
258258
except* BaseException as other: # catches every other sub-exception
259-
logger.error("Other grouped errors: %s", other.exceptions)
259+
logger.error(f"Other grouped errors: {other.exceptions}")
260260
raise other.exceptions[0]
261261

262262
async def list_gateways(self, db: Session, include_inactive: bool = False) -> List[GatewayRead]:

mcpgateway/services/prompt_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@
3030
# First-Party
3131
from mcpgateway.db import Prompt as DbPrompt
3232
from mcpgateway.db import PromptMetric, server_prompt_association
33-
from mcpgateway.models import Message, PromptResult, Role, TextContent
3433
from mcpgateway.schemas import PromptCreate, PromptRead, PromptUpdate
34+
from mcpgateway.models import Message, PromptResult, Role, TextContent
3535

3636
logger = logging.getLogger(__name__)
3737

mcpgateway/translate.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,11 @@
5555
import uuid
5656

5757
# Third-Party
58+
import uvicorn
59+
from sse_starlette.sse import EventSourceResponse
5860
from fastapi import FastAPI, Request, Response, status
5961
from fastapi.middleware.cors import CORSMiddleware
6062
from fastapi.responses import PlainTextResponse
61-
from sse_starlette.sse import EventSourceResponse
62-
import uvicorn
6363

6464
try:
6565
# Third-Party
@@ -135,7 +135,7 @@ async def start(self) -> None:
135135
136136
Creates the subprocess and starts the stdout pump task.
137137
"""
138-
LOGGER.info("Starting stdio subprocess: %s", self._cmd)
138+
LOGGER.info(f"Starting stdio subprocess: {self._cmd}")
139139
self._proc = await asyncio.create_subprocess_exec(
140140
*shlex.split(self._cmd),
141141
stdin=asyncio.subprocess.PIPE,
@@ -153,7 +153,7 @@ async def stop(self) -> None:
153153
"""
154154
if self._proc is None:
155155
return
156-
LOGGER.info("Stopping subprocess (pid=%s)", self._proc.pid)
156+
LOGGER.info(f"Stopping subprocess (pid={self._proc.pid})")
157157
self._proc.terminate()
158158
with suppress(asyncio.TimeoutError):
159159
await asyncio.wait_for(self._proc.wait(), timeout=5)
@@ -171,7 +171,7 @@ async def send(self, raw: str) -> None:
171171
"""
172172
if not self._stdin:
173173
raise RuntimeError("stdio endpoint not started")
174-
LOGGER.debug("→ stdio: %s", raw.strip())
174+
LOGGER.debug(f"→ stdio: {raw.strip()}")
175175
self._stdin.write(raw.encode())
176176
await self._stdin.drain()
177177

@@ -192,7 +192,7 @@ async def _pump_stdout(self) -> None:
192192
if not line: # EOF
193193
break
194194
text = line.decode(errors="replace")
195-
LOGGER.debug("← stdio: %s", text.strip())
195+
LOGGER.debug(f"← stdio: {text.strip()}")
196196
await self._pubsub.publish(text)
197197
except Exception: # pragma: no cover --best-effort logging
198198
LOGGER.exception("stdout pump crashed - terminating bridge")
@@ -420,7 +420,7 @@ async def _shutdown() -> None:
420420
with suppress(NotImplementedError): # Windows lacks add_signal_handler
421421
loop.add_signal_handler(sig, lambda: asyncio.create_task(_shutdown()))
422422

423-
LOGGER.info("Bridge ready → http://127.0.0.1:%s/sse", port)
423+
LOGGER.info(f"Bridge ready → http://127.0.0.1:{port}/sse")
424424
await server.serve()
425425
await _shutdown() # final cleanup
426426

mcpgateway/transports/streamablehttp_transport.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from mcpgateway.services.tool_service import ToolService
5151
from mcpgateway.utils.verify_credentials import verify_credentials
5252

53+
5354
logger = logging.getLogger(__name__)
5455
logging.basicConfig(level=logging.INFO)
5556

0 commit comments

Comments
 (0)