Skip to content

Commit 1f3a52a

Browse files
committed
linting
1 parent 656f9c2 commit 1f3a52a

File tree

2 files changed

+53
-39
lines changed

2 files changed

+53
-39
lines changed
Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
1-
from . import server
1+
# -*- coding: utf-8 -*-
2+
"""MCP Gateway Wrapper init file.
3+
4+
Copyright 2025
5+
SPDX-License-Identifier: Apache-2.0
6+
Authors: Keval Mahajan, Mihai Criveti, Madhav Kandukuri
7+
"""
8+
29
import asyncio
10+
from . import server
11+
312

413
def main():
514
"""Main entry point for the package."""
615
asyncio.run(server.main())
716

17+
818
# Optionally expose other important items at package level
9-
__all__ = ['main', 'server']
19+
__all__ = ["main", "server"]

mcpgateway-wrapper/src/mcpgateway_wrapper/server.py

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,55 @@
1+
# -*- coding: utf-8 -*-
2+
"""MCP Gateway Wrapper server.
3+
4+
Copyright 2025
5+
SPDX-License-Identifier: Apache-2.0
6+
Authors: Keval Mahajan, Mihai Criveti, Madhav Kandukuri
7+
8+
This module implements a wrapper bridge that facilitates
9+
interaction between the MCP client and the MCP gateway.
10+
It provides several functionalities, including listing tools, invoking tools, managing resources ,
11+
retrieving prompts, and handling tool calls via the MCP gateway.
12+
"""
13+
114
import asyncio
215
import os
3-
from typing import List, Dict, Any
4-
import jwt
5-
import datetime
16+
from typing import List, Dict, Any, Optional, Union
17+
from urllib.parse import urlparse
18+
619

720
import httpx
821
from pydantic import AnyUrl
922

10-
import mcp.types as types
23+
from mcp import types
1124
from mcp.server import NotificationOptions, Server
1225
from mcp.server.models import InitializationOptions
1326
import mcp.server.stdio
1427

15-
from urllib.parse import urlparse
1628

1729
def extract_base_url(url: str) -> str:
30+
"""
31+
Extracts the base URL (scheme + netloc) from a given URL string.
32+
33+
Args:
34+
url (str): The full URL string to be parsed.
35+
36+
Returns:
37+
str: The base URL, including the scheme (http, https) and the netloc (domain).
38+
39+
Example:
40+
>>> extract_base_url("https://www.example.com/path/to/resource")
41+
'https://www.example.com'
42+
"""
1843
parsed_url = urlparse(url)
1944
return f"{parsed_url.scheme}://{parsed_url.netloc}"
2045

46+
2147
# Default Values
2248

2349
mcp_servers_raw = os.getenv("MCP_SERVER_CATALOG_URLS", "")
2450
MCP_AUTH_TOKEN = os.getenv("MCP_AUTH_TOKEN", "")
2551

26-
mcp_servers_urls = (
27-
mcp_servers_raw.split(",") if "," in mcp_servers_raw else [mcp_servers_raw]
28-
)
52+
mcp_servers_urls = mcp_servers_raw.split(",") if "," in mcp_servers_raw else [mcp_servers_raw]
2953
BASE_URL = extract_base_url(mcp_servers_urls[0])
3054
TOOL_CALL_TIMEOUT = 90
3155

@@ -61,12 +85,7 @@ async def get_tools_from_mcp_server(catalog_urls: List[str]) -> List[str]:
6185
if response.status_code != 200:
6286
raise ValueError(f"Failed to fetch server catalog: {response.status_code}")
6387
server_catalog = response.json()
64-
tool_ids = [
65-
tool
66-
for server in server_catalog
67-
if str(server["id"]) in server_ids
68-
for tool in server["associatedTools"]
69-
]
88+
tool_ids = [tool for server in server_catalog if str(server["id"]) in server_ids for tool in server["associatedTools"]]
7089
return tool_ids
7190

7291

@@ -87,7 +106,7 @@ async def tools_metadata(tool_ids: List[str]) -> List[Dict[str, Any]]:
87106
raise ValueError(f"Failed to fetch tools metadata: {response.status_code}")
88107
all_tools = response.json()
89108
if tool_ids == [0]:
90-
return all_tools
109+
return all_tools
91110
tools = [tool for tool in all_tools if tool["id"] in tool_ids]
92111
return tools
93112

@@ -107,12 +126,7 @@ async def get_prompts_from_mcp_server(catalog_urls: List[str]) -> List[str]:
107126
if response.status_code != 200:
108127
raise ValueError(f"Failed to fetch server catalog: {response.status_code}")
109128
server_catalog = response.json()
110-
prompt_ids = [
111-
prompt
112-
for server in server_catalog
113-
if str(server["id"]) in server_ids
114-
for prompt in server.get("associatedPrompts", [])
115-
]
129+
prompt_ids = [prompt for server in server_catalog if str(server["id"]) in server_ids for prompt in server.get("associatedPrompts", [])]
116130
return prompt_ids
117131

118132

@@ -133,7 +147,7 @@ async def prompts_metadata(prompt_ids: List[str]) -> List[Dict[str, Any]]:
133147
raise ValueError(f"Failed to fetch prompts metadata: {response.status_code}")
134148
all_prompts = response.json()
135149
if prompt_ids == [0]:
136-
return all_prompts
150+
return all_prompts
137151
prompts = [prompt for prompt in all_prompts if prompt["id"] in prompt_ids]
138152
return prompts
139153

@@ -153,12 +167,7 @@ async def get_resources_from_mcp_server(catalog_urls: List[str]) -> List[str]:
153167
if response.status_code != 200:
154168
raise ValueError(f"Failed to fetch server catalog: {response.status_code}")
155169
server_catalog = response.json()
156-
resource_ids = [
157-
resource
158-
for server in server_catalog
159-
if str(server["id"]) in server_ids
160-
for resource in server.get("associatedResources", [])
161-
]
170+
resource_ids = [resource for server in server_catalog if str(server["id"]) in server_ids for resource in server.get("associatedResources", [])]
162171
return resource_ids
163172

164173

@@ -213,10 +222,9 @@ async def handle_list_tools() -> list[types.Tool]:
213222
except Exception as e:
214223
raise RuntimeError(f"Error listing tools: {e}")
215224

225+
216226
@server.call_tool()
217-
async def handle_call_tool(
218-
name: str, arguments: dict | None
219-
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
227+
async def handle_call_tool(name: str, arguments: Optional[dict] = None) -> list[Union[types.TextContent, types.ImageContent, types.EmbeddedResource]]:
220228
"""Handle tool execution requests.
221229
222230
Args:
@@ -255,9 +263,7 @@ async def handle_call_tool(
255263
except httpx.RequestError as e:
256264
raise ConnectionError(f"An error occurred while calling tool {name}: {e}")
257265
except httpx.HTTPStatusError as e:
258-
raise RuntimeError(
259-
f"Tool call failed with status code {e.response.status_code}"
260-
)
266+
raise RuntimeError(f"Tool call failed with status code {e.response.status_code}")
261267
except Exception as e:
262268
raise RuntimeError(f"Unexpected error calling tool: {e}")
263269

@@ -335,9 +341,7 @@ async def handle_list_prompts() -> list[types.Prompt]:
335341

336342

337343
@server.get_prompt()
338-
async def handle_get_prompt(
339-
name: str, arguments: dict[str, str] | None
340-
) -> types.GetPromptResult:
344+
async def handle_get_prompt(name: str, arguments: Optional[dict[str, str]] = None) -> types.GetPromptResult:
341345
"""Generate a prompt by combining the remote prompt template with provided arguments.
342346
343347
Args:

0 commit comments

Comments
 (0)