Skip to content

Commit eb410fe

Browse files
committed
Format with ruff
1 parent 9ac97e8 commit eb410fe

File tree

14 files changed

+259
-92
lines changed

14 files changed

+259
-92
lines changed

mcp_python/__init__.py

Lines changed: 3 additions & 1 deletion
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

Lines changed: 2 additions & 1 deletion
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

Lines changed: 19 additions & 5 deletions
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

Lines changed: 2 additions & 1 deletion
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

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def request_context(self) -> RequestContext:
6060

6161
def list_prompts(self):
6262
def decorator(func: Callable[[], Awaitable[list[Prompt]]]):
63-
logger.debug(f"Registering handler for PromptListRequest")
63+
logger.debug("Registering handler for PromptListRequest")
6464

6565
async def handler(_: Any):
6666
prompts = await func()
@@ -76,17 +76,19 @@ def get_prompt(self):
7676
GetPromptRequest,
7777
GetPromptResult,
7878
ImageContent,
79-
Role as Role,
8079
SamplingMessage,
8180
TextContent,
8281
)
82+
from mcp_python.types import (
83+
Role as Role,
84+
)
8385

8486
def decorator(
8587
func: Callable[
8688
[str, dict[str, str] | None], Awaitable[types.PromptResponse]
8789
],
8890
):
89-
logger.debug(f"Registering handler for GetPromptRequest")
91+
logger.debug("Registering handler for GetPromptRequest")
9092

9193
async def handler(req: GetPromptRequest):
9294
prompt_get = await func(req.params.name, req.params.arguments)
@@ -122,7 +124,7 @@ async def handler(req: GetPromptRequest):
122124

123125
def list_resources(self):
124126
def decorator(func: Callable[[], Awaitable[list[Resource]]]):
125-
logger.debug(f"Registering handler for ListResourcesRequest")
127+
logger.debug("Registering handler for ListResourcesRequest")
126128

127129
async def handler(_: Any):
128130
resources = await func()
@@ -142,7 +144,7 @@ def read_resource(self):
142144
)
143145

144146
def decorator(func: Callable[[AnyUrl], Awaitable[str | bytes]]):
145-
logger.debug(f"Registering handler for ReadResourceRequest")
147+
logger.debug("Registering handler for ReadResourceRequest")
146148

147149
async def handler(req: ReadResourceRequest):
148150
result = await func(req.params.uri)
@@ -177,7 +179,7 @@ def set_logging_level(self):
177179
from mcp_python.types import EmptyResult
178180

179181
def decorator(func: Callable[[LoggingLevel], Awaitable[None]]):
180-
logger.debug(f"Registering handler for SetLevelRequest")
182+
logger.debug("Registering handler for SetLevelRequest")
181183

182184
async def handler(req: SetLevelRequest):
183185
await func(req.params.level)
@@ -192,7 +194,7 @@ def subscribe_resource(self):
192194
from mcp_python.types import EmptyResult
193195

194196
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
195-
logger.debug(f"Registering handler for SubscribeRequest")
197+
logger.debug("Registering handler for SubscribeRequest")
196198

197199
async def handler(req: SubscribeRequest):
198200
await func(req.params.uri)
@@ -207,7 +209,7 @@ def unsubscribe_resource(self):
207209
from mcp_python.types import EmptyResult
208210

209211
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
210-
logger.debug(f"Registering handler for UnsubscribeRequest")
212+
logger.debug("Registering handler for UnsubscribeRequest")
211213

212214
async def handler(req: UnsubscribeRequest):
213215
await func(req.params.uri)
@@ -222,7 +224,7 @@ def call_tool(self):
222224
from mcp_python.types import CallToolResult
223225

224226
def decorator(func: Callable[..., Awaitable[Any]]):
225-
logger.debug(f"Registering handler for CallToolRequest")
227+
logger.debug("Registering handler for CallToolRequest")
226228

227229
async def handler(req: CallToolRequest):
228230
result = await func(req.params.name, **(req.params.arguments or {}))
@@ -237,7 +239,7 @@ def progress_notification(self):
237239
def decorator(
238240
func: Callable[[str | int, float, float | None], Awaitable[None]],
239241
):
240-
logger.debug(f"Registering handler for ProgressNotification")
242+
logger.debug("Registering handler for ProgressNotification")
241243

242244
async def handler(req: ProgressNotification):
243245
await func(
@@ -259,7 +261,7 @@ def decorator(
259261
Awaitable[Completion | None],
260262
],
261263
):
262-
logger.debug(f"Registering handler for CompleteRequest")
264+
logger.debug("Registering handler for CompleteRequest")
263265

264266
async def handler(req: CompleteRequest):
265267
completion = await func(req.params.ref, req.params.argument)
@@ -293,10 +295,12 @@ async def run(
293295
self,
294296
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
295297
write_stream: MemoryObjectSendStream[JSONRPCMessage],
296-
initialization_options: InitializationOptions
298+
initialization_options: InitializationOptions,
297299
):
298300
with warnings.catch_warnings(record=True) as w:
299-
async with ServerSession(read_stream, write_stream, initialization_options) as session:
301+
async with ServerSession(
302+
read_stream, write_stream, initialization_options
303+
) as session:
300304
async for message in session.incoming_messages:
301305
logger.debug(f"Received message: {message}")
302306

@@ -345,14 +349,16 @@ async def run(
345349

346350
handler = self.notification_handlers[type(notify)]
347351
logger.debug(
348-
f"Dispatching notification of type {type(notify).__name__}"
352+
f"Dispatching notification of type "
353+
f"{type(notify).__name__}"
349354
)
350355

351356
try:
352357
await handler(notify)
353358
except Exception as err:
354359
logger.error(
355-
f"Uncaught exception in notification handler: {err}"
360+
f"Uncaught exception in notification handler: "
361+
f"{err}"
356362
)
357363

358364
for warning in w:

mcp_python/server/__main__.py

Lines changed: 14 additions & 2 deletions
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 InitializationOptions, ServerSession
@@ -29,7 +30,18 @@ async def receive_loop(session: ServerSession):
2930
async def main():
3031
version = importlib.metadata.version("mcp_python")
3132
async with stdio_server() as (read_stream, write_stream):
32-
async with ServerSession(read_stream, write_stream, InitializationOptions(server_name="mcp_python", server_version=version, capabilities=ServerCapabilities())) as session, write_stream:
33+
async with (
34+
ServerSession(
35+
read_stream,
36+
write_stream,
37+
InitializationOptions(
38+
server_name="mcp_python",
39+
server_version=version,
40+
capabilities=ServerCapabilities(),
41+
),
42+
) as session,
43+
write_stream,
44+
):
3345
await receive_loop(session)
3446

3547

mcp_python/server/session.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
from dataclasses import dataclass
12
from enum import Enum
23
from typing import Any
3-
from dataclasses import dataclass
44

55
import anyio
66
import anyio.lowlevel
@@ -44,6 +44,7 @@ class InitializationOptions:
4444
server_version: str
4545
capabilities: ServerCapabilities
4646

47+
4748
class ServerSession(
4849
BaseSession[
4950
ServerRequest,
@@ -59,7 +60,7 @@ def __init__(
5960
self,
6061
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
6162
write_stream: MemoryObjectSendStream[JSONRPCMessage],
62-
init_options: InitializationOptions
63+
init_options: InitializationOptions,
6364
) -> None:
6465
super().__init__(read_stream, write_stream, ClientRequest, ClientNotification)
6566
self._initialization_state = InitializationState.NotInitialized
@@ -78,7 +79,7 @@ async def _received_request(
7879
capabilities=self._init_options.capabilities,
7980
serverInfo=Implementation(
8081
name=self._init_options.server_name,
81-
version=self._init_options.server_version
82+
version=self._init_options.server_version,
8283
),
8384
)
8485
)

mcp_python/server/sse.py

Lines changed: 13 additions & 6 deletions
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

Lines changed: 10 additions & 4 deletions
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:
@@ -47,7 +51,9 @@ async def stdout_writer():
4751
try:
4852
async with write_stream_reader:
4953
async for message in write_stream_reader:
50-
json = message.model_dump_json(by_alias=True, exclude_none=True)
54+
json = message.model_dump_json(
55+
by_alias=True, exclude_none=True
56+
)
5157
await stdout.write(json + "\n")
5258
await stdout.flush()
5359
except anyio.ClosedResourceError:

mcp_python/server/websocket.py

Lines changed: 5 additions & 2 deletions
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)