Skip to content

Commit 7652177

Browse files
committed
Return 502 from admin endpoint too
Signed-off-by: Madhav Kandukuri <[email protected]>
1 parent c5ca000 commit 7652177

File tree

4 files changed

+22
-41
lines changed

4 files changed

+22
-41
lines changed

mcpgateway/admin.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
ToolRead,
4949
ToolUpdate,
5050
)
51-
from mcpgateway.services.gateway_service import GatewayService
51+
from mcpgateway.services.gateway_service import GatewayService, GatewayConnectionError
5252
from mcpgateway.services.prompt_service import PromptService
5353
from mcpgateway.services.resource_service import ResourceService
5454
from mcpgateway.services.root_service import RootService
@@ -762,10 +762,13 @@ async def admin_add_gateway(request: Request, db: Session = Depends(get_db), use
762762
auth_header_key=form.get("auth_header_key", ""),
763763
auth_header_value=form.get("auth_header_value", ""),
764764
)
765-
await gateway_service.register_gateway(db, gateway)
766-
767765
root_path = request.scope.get("root_path", "")
768-
return RedirectResponse(f"{root_path}/admin#gateways", status_code=303)
766+
try:
767+
await gateway_service.register_gateway(db, gateway)
768+
return RedirectResponse(f"{root_path}/admin#gateways", status_code=303)
769+
except Exception as ex:
770+
if isinstance(ex, GatewayConnectionError):
771+
return RedirectResponse(f"{root_path}/admin#gateways", status_code=502)
769772

770773

771774
@admin_router.post("/gateways/{gateway_id}/edit")

mcpgateway/main.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import asyncio
2929
import json
3030
import logging
31-
import os
3231
from contextlib import asynccontextmanager
3332
from typing import Any, AsyncIterator, Dict, List, Optional, Union
3433

@@ -78,7 +77,7 @@
7877
ToolUpdate,
7978
)
8079
from mcpgateway.services.completion_service import CompletionService
81-
from mcpgateway.services.gateway_service import GatewayService, GatewayConnectionError
80+
from mcpgateway.services.gateway_service import GatewayConnectionError, GatewayService
8281
from mcpgateway.services.logging_service import LoggingService
8382
from mcpgateway.services.prompt_service import (
8483
PromptError,
@@ -1510,11 +1509,7 @@ async def register_gateway(
15101509
return await gateway_service.register_gateway(db, gateway)
15111510
except Exception as ex:
15121511
if isinstance(ex, GatewayConnectionError):
1513-
return JSONResponse(
1514-
content={"message": "Unable to connect to gateway"},
1515-
status_code=502
1516-
)
1517-
1512+
return JSONResponse(content={"message": "Unable to connect to gateway"}, status_code=502)
15181513

15191514

15201515
@gateway_router.get("/{gateway_id}", response_model=GatewayRead)

mcpgateway/services/gateway_service.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,11 @@ def __init__(self):
123123
self._redis_client = None
124124

125125
async def initialize(self) -> None:
126-
"""Initialize the service and start health check if this instance is the leader."""
126+
"""Initialize the service and start health check if this instance is the leader.
127+
128+
Raises:
129+
ConnectionError: When redis ping fails
130+
"""
127131
logger.info("Initializing gateway service")
128132

129133
if self._redis_client:
@@ -166,6 +170,7 @@ async def register_gateway(self, db: Session, gateway: GatewayCreate) -> Gateway
166170
167171
Raises:
168172
GatewayNameConflictError: If gateway name already exists
173+
[]: When ExceptionGroup found
169174
"""
170175
try:
171176
# Check for name conflicts (both active and inactive)
@@ -232,16 +237,18 @@ async def register_gateway(self, db: Session, gateway: GatewayCreate) -> Gateway
232237
await self._notify_gateway_added(db_gateway)
233238

234239
return GatewayRead.model_validate(gateway)
235-
except* GatewayConnectionError as ve:
236-
logger.error("GatewayConnectionError in group: %s", ve.exceptions)
237-
raise ve.exceptions[0]
240+
except* GatewayConnectionError as ge:
241+
logger.error("GatewayConnectionError in group: %s", ge.exceptions)
242+
raise ge.exceptions[0]
238243
except* ValueError as ve:
239244
logger.error("ValueErrors in group: %s", ve.exceptions)
245+
raise ve.exceptions[0]
240246
except* RuntimeError as re:
241247
logger.error("RuntimeErrors in group: %s", re.exceptions)
248+
raise re.exceptions[0]
242249
except* BaseException as other: # catches every other sub-exception
243250
logger.error("Other grouped errors: %s", other.exceptions)
244-
raise Exception(other.exceptions)
251+
raise other.exceptions[0]
245252

246253
async def list_gateways(self, db: Session, include_inactive: bool = False) -> List[GatewayRead]:
247254
"""List all registered gateways.

mcpgateway/wrapper.py

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _extract_base_url(url: str) -> str:
9393
if not parsed.scheme or not parsed.netloc:
9494
raise ValueError(f"Invalid URL provided: {url}")
9595

96-
before_servers = parsed.path.split('/servers')[0]
96+
before_servers = parsed.path.split("/servers")[0]
9797
return f"{parsed.scheme}://{parsed.netloc}{before_servers}"
9898

9999

@@ -159,10 +159,6 @@ async def get_tools_from_mcp_server(catalog_urls: List[str]) -> List[str]:
159159
160160
Returns:
161161
List[str]: A list of tool ID strings extracted from the server catalog.
162-
163-
Raises:
164-
httpx.RequestError: If a network problem occurs.
165-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
166162
"""
167163
server_ids = [url.split("/")[-1] for url in catalog_urls]
168164
url = f"{BASE_URL}/servers/"
@@ -184,10 +180,6 @@ async def tools_metadata(tool_ids: List[str]) -> List[Dict[str, Any]]:
184180
185181
Returns:
186182
List[Dict[str, Any]]: A list of metadata dictionaries for each tool.
187-
188-
Raises:
189-
httpx.RequestError: If a network problem occurs.
190-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
191183
"""
192184
if not tool_ids:
193185
return []
@@ -209,10 +201,6 @@ async def get_prompts_from_mcp_server(catalog_urls: List[str]) -> List[str]:
209201
210202
Returns:
211203
List[str]: A list of prompt ID strings.
212-
213-
Raises:
214-
httpx.RequestError: If a network problem occurs.
215-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
216204
"""
217205
server_ids = [url.split("/")[-1] for url in catalog_urls]
218206
url = f"{BASE_URL}/servers/"
@@ -234,10 +222,6 @@ async def prompts_metadata(prompt_ids: List[str]) -> List[Dict[str, Any]]:
234222
235223
Returns:
236224
List[Dict[str, Any]]: A list of metadata dictionaries for each prompt.
237-
238-
Raises:
239-
httpx.RequestError: If a network problem occurs.
240-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
241225
"""
242226
if not prompt_ids:
243227
return []
@@ -258,10 +242,6 @@ async def get_resources_from_mcp_server(catalog_urls: List[str]) -> List[str]:
258242
259243
Returns:
260244
List[str]: A list of resource ID strings.
261-
262-
Raises:
263-
httpx.RequestError: If a network problem occurs.
264-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
265245
"""
266246
server_ids = [url.split("/")[-1] for url in catalog_urls]
267247
url = f"{BASE_URL}/servers/"
@@ -283,10 +263,6 @@ async def resources_metadata(resource_ids: List[str]) -> List[Dict[str, Any]]:
283263
284264
Returns:
285265
List[Dict[str, Any]]: A list of metadata dictionaries for each resource.
286-
287-
Raises:
288-
httpx.RequestError: If a network problem occurs.
289-
httpx.HTTPStatusError: If the server returns a 4xx or 5xx response.
290266
"""
291267
if not resource_ids:
292268
return []

0 commit comments

Comments
 (0)