Skip to content

Commit fe92991

Browse files
committed
Format with ruff
1 parent 3b5b4a4 commit fe92991

14 files changed

+255
-90
lines changed

mcp_python/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
ReadResourceResult,
3838
Resource,
3939
ResourceUpdatedNotification,
40-
Role as SamplingRole,
4140
SamplingMessage,
4241
ServerCapabilities,
4342
ServerNotification,
@@ -49,6 +48,9 @@
4948
Tool,
5049
UnsubscribeRequest,
5150
)
51+
from .types import (
52+
Role as SamplingRole,
53+
)
5254

5355
__all__ = [
5456
"CallToolRequest",

mcp_python/client/session.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ async def initialize(self) -> InitializeResult:
6262

6363
if result.protocolVersion != SUPPORTED_PROTOCOL_VERSION:
6464
raise RuntimeError(
65-
f"Unsupported protocol version from the server: {result.protocolVersion}"
65+
"Unsupported protocol version from the server: "
66+
f"{result.protocolVersion}"
6667
)
6768

6869
await self.send_notification(

mcp_python/client/sse.py

+19-5
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,17 @@ def remove_request_params(url: str) -> str:
1919

2020

2121
@asynccontextmanager
22-
async def sse_client(url: str, headers: dict[str, Any] | None = None, timeout: float = 5, sse_read_timeout: float = 60 * 5):
22+
async def sse_client(
23+
url: str,
24+
headers: dict[str, Any] | None = None,
25+
timeout: float = 5,
26+
sse_read_timeout: float = 60 * 5,
27+
):
2328
"""
2429
Client transport for SSE.
2530
26-
`sse_read_timeout` determines how long (in seconds) the client will wait for a new event before disconnecting. All other HTTP operations are controlled by `timeout`.
31+
`sse_read_timeout` determines how long (in seconds) the client will wait for a new
32+
event before disconnecting. All other HTTP operations are controlled by `timeout`.
2733
"""
2834
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception]
2935
read_stream_writer: MemoryObjectSendStream[JSONRPCMessage | Exception]
@@ -67,7 +73,10 @@ async def sse_reader(
6773
or url_parsed.scheme
6874
!= endpoint_parsed.scheme
6975
):
70-
error_msg = f"Endpoint origin does not match connection origin: {endpoint_url}"
76+
error_msg = (
77+
"Endpoint origin does not match "
78+
f"connection origin: {endpoint_url}"
79+
)
7180
logger.error(error_msg)
7281
raise ValueError(error_msg)
7382

@@ -104,11 +113,16 @@ async def post_writer(endpoint_url: str):
104113
logger.debug(f"Sending client message: {message}")
105114
response = await client.post(
106115
endpoint_url,
107-
json=message.model_dump(by_alias=True, mode="json", exclude_none=True),
116+
json=message.model_dump(
117+
by_alias=True,
118+
mode="json",
119+
exclude_none=True,
120+
),
108121
)
109122
response.raise_for_status()
110123
logger.debug(
111-
f"Client message sent successfully: {response.status_code}"
124+
"Client message sent successfully: "
125+
f"{response.status_code}"
112126
)
113127
except Exception as exc:
114128
logger.error(f"Error in post_writer: {exc}")

mcp_python/client/stdio.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ class StdioServerParameters(BaseModel):
2828
@asynccontextmanager
2929
async def stdio_client(server: StdioServerParameters):
3030
"""
31-
Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
31+
Client transport for stdio: this will connect to a server by spawning a
32+
process and communicating with it over stdin/stdout.
3233
"""
3334
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception]
3435
read_stream_writer: MemoryObjectSendStream[JSONRPCMessage | Exception]

mcp_python/server/__init__.py

+22-16
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@
4545
"request_ctx"
4646
)
4747

48-
4948
class Server:
5049
def __init__(self, name: str):
5150
self.name = name
@@ -75,7 +74,7 @@ def request_context(self) -> RequestContext:
7574

7675
def list_prompts(self):
7776
def decorator(func: Callable[[], Awaitable[list[Prompt]]]):
78-
logger.debug(f"Registering handler for PromptListRequest")
77+
logger.debug("Registering handler for PromptListRequest")
7978

8079
async def handler(_: Any):
8180
prompts = await func()
@@ -91,17 +90,19 @@ def get_prompt(self):
9190
GetPromptRequest,
9291
GetPromptResult,
9392
ImageContent,
94-
Role as Role,
9593
SamplingMessage,
9694
TextContent,
9795
)
96+
from mcp_python.types import (
97+
Role as Role,
98+
)
9899

99100
def decorator(
100101
func: Callable[
101102
[str, dict[str, str] | None], Awaitable[types.PromptResponse]
102103
],
103104
):
104-
logger.debug(f"Registering handler for GetPromptRequest")
105+
logger.debug("Registering handler for GetPromptRequest")
105106

106107
async def handler(req: GetPromptRequest):
107108
prompt_get = await func(req.params.name, req.params.arguments)
@@ -137,7 +138,7 @@ async def handler(req: GetPromptRequest):
137138

138139
def list_resources(self):
139140
def decorator(func: Callable[[], Awaitable[list[Resource]]]):
140-
logger.debug(f"Registering handler for ListResourcesRequest")
141+
logger.debug("Registering handler for ListResourcesRequest")
141142

142143
async def handler(_: Any):
143144
resources = await func()
@@ -157,7 +158,7 @@ def read_resource(self):
157158
)
158159

159160
def decorator(func: Callable[[AnyUrl], Awaitable[str | bytes]]):
160-
logger.debug(f"Registering handler for ReadResourceRequest")
161+
logger.debug("Registering handler for ReadResourceRequest")
161162

162163
async def handler(req: ReadResourceRequest):
163164
result = await func(req.params.uri)
@@ -192,7 +193,7 @@ def set_logging_level(self):
192193
from mcp_python.types import EmptyResult
193194

194195
def decorator(func: Callable[[LoggingLevel], Awaitable[None]]):
195-
logger.debug(f"Registering handler for SetLevelRequest")
196+
logger.debug("Registering handler for SetLevelRequest")
196197

197198
async def handler(req: SetLevelRequest):
198199
await func(req.params.level)
@@ -207,7 +208,7 @@ def subscribe_resource(self):
207208
from mcp_python.types import EmptyResult
208209

209210
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
210-
logger.debug(f"Registering handler for SubscribeRequest")
211+
logger.debug("Registering handler for SubscribeRequest")
211212

212213
async def handler(req: SubscribeRequest):
213214
await func(req.params.uri)
@@ -222,7 +223,7 @@ def unsubscribe_resource(self):
222223
from mcp_python.types import EmptyResult
223224

224225
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
225-
logger.debug(f"Registering handler for UnsubscribeRequest")
226+
logger.debug("Registering handler for UnsubscribeRequest")
226227

227228
async def handler(req: UnsubscribeRequest):
228229
await func(req.params.uri)
@@ -237,7 +238,7 @@ def call_tool(self):
237238
from mcp_python.types import CallToolResult
238239

239240
def decorator(func: Callable[..., Awaitable[Any]]):
240-
logger.debug(f"Registering handler for CallToolRequest")
241+
logger.debug("Registering handler for CallToolRequest")
241242

242243
async def handler(req: CallToolRequest):
243244
result = await func(req.params.name, **(req.params.arguments or {}))
@@ -252,7 +253,7 @@ def progress_notification(self):
252253
def decorator(
253254
func: Callable[[str | int, float, float | None], Awaitable[None]],
254255
):
255-
logger.debug(f"Registering handler for ProgressNotification")
256+
logger.debug("Registering handler for ProgressNotification")
256257

257258
async def handler(req: ProgressNotification):
258259
await func(
@@ -274,7 +275,7 @@ def decorator(
274275
Awaitable[Completion | None],
275276
],
276277
):
277-
logger.debug(f"Registering handler for CompleteRequest")
278+
logger.debug("Registering handler for CompleteRequest")
278279

279280
async def handler(req: CompleteRequest):
280281
completion = await func(req.params.ref, req.params.argument)
@@ -293,14 +294,15 @@ async def handler(req: CompleteRequest):
293294

294295
def get_capabilities(self) -> ServerCapabilities:
295296
"""Convert existing handlers to a ServerCapabilities object."""
297+
296298
def get_capability(req_type: type) -> dict[str, Any] | None:
297299
return {} if req_type in self.request_handlers else None
298300

299301
return ServerCapabilities(
300302
prompts=get_capability(ListPromptsRequest),
301303
resources=get_capability(ListResourcesRequest),
302304
tools=get_capability(ListPromptsRequest),
303-
logging=get_capability(SetLevelRequest)
305+
logging=get_capability(SetLevelRequest),
304306
)
305307

306308
async def run(
@@ -310,7 +312,9 @@ async def run(
310312
initialization_options: types.InitializationOptions
311313
):
312314
with warnings.catch_warnings(record=True) as w:
313-
async with ServerSession(read_stream, write_stream, initialization_options) as session:
315+
async with ServerSession(
316+
read_stream, write_stream, initialization_options
317+
) as session:
314318
async for message in session.incoming_messages:
315319
logger.debug(f"Received message: {message}")
316320

@@ -359,14 +363,16 @@ async def run(
359363

360364
handler = self.notification_handlers[type(notify)]
361365
logger.debug(
362-
f"Dispatching notification of type {type(notify).__name__}"
366+
f"Dispatching notification of type "
367+
f"{type(notify).__name__}"
363368
)
364369

365370
try:
366371
await handler(notify)
367372
except Exception as err:
368373
logger.error(
369-
f"Uncaught exception in notification handler: {err}"
374+
f"Uncaught exception in notification handler: "
375+
f"{err}"
370376
)
371377

372378
for warning in w:

mcp_python/server/__main__.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import importlib.metadata
12
import logging
23
import sys
3-
import importlib.metadata
4+
45
import anyio
56

67
from mcp_python.server.session import ServerSession
@@ -30,7 +31,18 @@ async def receive_loop(session: ServerSession):
3031
async def main():
3132
version = importlib.metadata.version("mcp_python")
3233
async with stdio_server() as (read_stream, write_stream):
33-
async with ServerSession(read_stream, write_stream, InitializationOptions(server_name="mcp_python", server_version=version, capabilities=ServerCapabilities())) as session, write_stream:
34+
async with (
35+
ServerSession(
36+
read_stream,
37+
write_stream,
38+
InitializationOptions(
39+
server_name="mcp_python",
40+
server_version=version,
41+
capabilities=ServerCapabilities(),
42+
),
43+
) as session,
44+
write_stream,
45+
):
3446
await receive_loop(session)
3547

3648

mcp_python/server/session.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from dataclasses import dataclass
12
from enum import Enum
23
from typing import Any
34

@@ -72,7 +73,7 @@ async def _received_request(
7273
capabilities=self._init_options.capabilities,
7374
serverInfo=Implementation(
7475
name=self._init_options.server_name,
75-
version=self._init_options.server_version
76+
version=self._init_options.server_version,
7677
),
7778
)
7879
)

mcp_python/server/sse.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,23 @@
1919

2020
class SseServerTransport:
2121
"""
22-
SSE server transport for MCP. This class provides _two_ ASGI applications, suitable to be used with a framework like Starlette and a server like Hypercorn:
23-
24-
1. connect_sse() is an ASGI application which receives incoming GET requests, and sets up a new SSE stream to send server messages to the client.
25-
2. handle_post_message() is an ASGI application which receives incoming POST requests, which should contain client messages that link to a previously-established SSE session.
22+
SSE server transport for MCP. This class provides _two_ ASGI applications,
23+
suitable to be used with a framework like Starlette and a server like Hypercorn:
24+
25+
1. connect_sse() is an ASGI application which receives incoming GET requests,
26+
and sets up a new SSE stream to send server messages to the client.
27+
2. handle_post_message() is an ASGI application which receives incoming POST
28+
requests, which should contain client messages that link to a
29+
previously-established SSE session.
2630
"""
2731

2832
_endpoint: str
2933
_read_stream_writers: dict[UUID, MemoryObjectSendStream[JSONRPCMessage | Exception]]
3034

3135
def __init__(self, endpoint: str) -> None:
3236
"""
33-
Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL given.
37+
Creates a new SSE server transport, which will direct the client to POST
38+
messages to the relative or absolute URL given.
3439
"""
3540

3641
super().__init__()
@@ -74,7 +79,9 @@ async def sse_writer():
7479
await sse_stream_writer.send(
7580
{
7681
"event": "message",
77-
"data": message.model_dump_json(by_alias=True, exclude_none=True),
82+
"data": message.model_dump_json(
83+
by_alias=True, exclude_none=True
84+
),
7885
}
7986
)
8087

mcp_python/server/stdio.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,18 @@
77

88
from mcp_python.types import JSONRPCMessage
99

10+
1011
@asynccontextmanager
1112
async def stdio_server(
12-
stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.AsyncFile[str] | None = None
13+
stdin: anyio.AsyncFile[str] | None = None,
14+
stdout: anyio.AsyncFile[str] | None = None,
1315
):
1416
"""
15-
Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.
17+
Server transport for stdio: this communicates with an MCP client by reading
18+
from the current process' stdin and writing to stdout.
1619
"""
17-
# Purposely not using context managers for these, as we don't want to close standard process handles.
20+
# Purposely not using context managers for these, as we don't want to close
21+
# standard process handles.
1822
if not stdin:
1923
stdin = anyio.wrap_file(sys.stdin)
2024
if not stdout:

mcp_python/server/websocket.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
@asynccontextmanager
1515
async def websocket_server(scope: Scope, receive: Receive, send: Send):
1616
"""
17-
WebSocket server transport for MCP. This is an ASGI application, suitable to be used with a framework like Starlette and a server like Hypercorn.
17+
WebSocket server transport for MCP. This is an ASGI application, suitable to be
18+
used with a framework like Starlette and a server like Hypercorn.
1819
"""
1920

2021
websocket = WebSocket(scope, receive, send)
@@ -47,7 +48,9 @@ async def ws_writer():
4748
try:
4849
async with write_stream_reader:
4950
async for message in write_stream_reader:
50-
obj = message.model_dump(by_alias=True, mode="json", exclude_none=True)
51+
obj = message.model_dump(
52+
by_alias=True, mode="json", exclude_none=True
53+
)
5154
await websocket.send_json(obj)
5255
except anyio.ClosedResourceError:
5356
await websocket.close()

0 commit comments

Comments
 (0)