Skip to content

Commit ac4a344

Browse files
committed
Format with ruff
1 parent 9475815 commit ac4a344

File tree

14 files changed

+267
-99
lines changed

14 files changed

+267
-99
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: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,11 @@ def __init__(self, name: str):
5555

5656
def create_initialization_options(self) -> types.InitializationOptions:
5757
"""Create initialization options from this server instance."""
58+
5859
def pkg_version(package: str) -> str:
5960
try:
6061
from importlib.metadata import version
62+
6163
return version(package)
6264
except Exception:
6365
return "unknown"
@@ -69,16 +71,17 @@ def pkg_version(package: str) -> str:
6971
)
7072

7173
def get_capabilities(self) -> ServerCapabilities:
72-
"""Convert existing handlers to a ServerCapabilities object."""
73-
def get_capability(req_type: type) -> dict[str, Any] | None:
74-
return {} if req_type in self.request_handlers else None
74+
"""Convert existing handlers to a ServerCapabilities object."""
7575

76-
return ServerCapabilities(
77-
prompts=get_capability(ListPromptsRequest),
78-
resources=get_capability(ListResourcesRequest),
79-
tools=get_capability(ListPromptsRequest),
80-
logging=get_capability(SetLevelRequest)
81-
)
76+
def get_capability(req_type: type) -> dict[str, Any] | None:
77+
return {} if req_type in self.request_handlers else None
78+
79+
return ServerCapabilities(
80+
prompts=get_capability(ListPromptsRequest),
81+
resources=get_capability(ListResourcesRequest),
82+
tools=get_capability(ListPromptsRequest),
83+
logging=get_capability(SetLevelRequest),
84+
)
8285

8386
@property
8487
def request_context(self) -> RequestContext:
@@ -87,7 +90,7 @@ def request_context(self) -> RequestContext:
8790

8891
def list_prompts(self):
8992
def decorator(func: Callable[[], Awaitable[list[Prompt]]]):
90-
logger.debug(f"Registering handler for PromptListRequest")
93+
logger.debug("Registering handler for PromptListRequest")
9194

9295
async def handler(_: Any):
9396
prompts = await func()
@@ -103,17 +106,19 @@ def get_prompt(self):
103106
GetPromptRequest,
104107
GetPromptResult,
105108
ImageContent,
106-
Role as Role,
107109
SamplingMessage,
108110
TextContent,
109111
)
112+
from mcp_python.types import (
113+
Role as Role,
114+
)
110115

111116
def decorator(
112117
func: Callable[
113118
[str, dict[str, str] | None], Awaitable[types.PromptResponse]
114119
],
115120
):
116-
logger.debug(f"Registering handler for GetPromptRequest")
121+
logger.debug("Registering handler for GetPromptRequest")
117122

118123
async def handler(req: GetPromptRequest):
119124
prompt_get = await func(req.params.name, req.params.arguments)
@@ -149,7 +154,7 @@ async def handler(req: GetPromptRequest):
149154

150155
def list_resources(self):
151156
def decorator(func: Callable[[], Awaitable[list[Resource]]]):
152-
logger.debug(f"Registering handler for ListResourcesRequest")
157+
logger.debug("Registering handler for ListResourcesRequest")
153158

154159
async def handler(_: Any):
155160
resources = await func()
@@ -169,7 +174,7 @@ def read_resource(self):
169174
)
170175

171176
def decorator(func: Callable[[AnyUrl], Awaitable[str | bytes]]):
172-
logger.debug(f"Registering handler for ReadResourceRequest")
177+
logger.debug("Registering handler for ReadResourceRequest")
173178

174179
async def handler(req: ReadResourceRequest):
175180
result = await func(req.params.uri)
@@ -204,7 +209,7 @@ def set_logging_level(self):
204209
from mcp_python.types import EmptyResult
205210

206211
def decorator(func: Callable[[LoggingLevel], Awaitable[None]]):
207-
logger.debug(f"Registering handler for SetLevelRequest")
212+
logger.debug("Registering handler for SetLevelRequest")
208213

209214
async def handler(req: SetLevelRequest):
210215
await func(req.params.level)
@@ -219,7 +224,7 @@ def subscribe_resource(self):
219224
from mcp_python.types import EmptyResult
220225

221226
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
222-
logger.debug(f"Registering handler for SubscribeRequest")
227+
logger.debug("Registering handler for SubscribeRequest")
223228

224229
async def handler(req: SubscribeRequest):
225230
await func(req.params.uri)
@@ -234,7 +239,7 @@ def unsubscribe_resource(self):
234239
from mcp_python.types import EmptyResult
235240

236241
def decorator(func: Callable[[AnyUrl], Awaitable[None]]):
237-
logger.debug(f"Registering handler for UnsubscribeRequest")
242+
logger.debug("Registering handler for UnsubscribeRequest")
238243

239244
async def handler(req: UnsubscribeRequest):
240245
await func(req.params.uri)
@@ -249,7 +254,7 @@ def call_tool(self):
249254
from mcp_python.types import CallToolResult
250255

251256
def decorator(func: Callable[..., Awaitable[Any]]):
252-
logger.debug(f"Registering handler for CallToolRequest")
257+
logger.debug("Registering handler for CallToolRequest")
253258

254259
async def handler(req: CallToolRequest):
255260
result = await func(req.params.name, **(req.params.arguments or {}))
@@ -264,7 +269,7 @@ def progress_notification(self):
264269
def decorator(
265270
func: Callable[[str | int, float, float | None], Awaitable[None]],
266271
):
267-
logger.debug(f"Registering handler for ProgressNotification")
272+
logger.debug("Registering handler for ProgressNotification")
268273

269274
async def handler(req: ProgressNotification):
270275
await func(
@@ -286,7 +291,7 @@ def decorator(
286291
Awaitable[Completion | None],
287292
],
288293
):
289-
logger.debug(f"Registering handler for CompleteRequest")
294+
logger.debug("Registering handler for CompleteRequest")
290295

291296
async def handler(req: CompleteRequest):
292297
completion = await func(req.params.ref, req.params.argument)
@@ -307,10 +312,12 @@ async def run(
307312
self,
308313
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
309314
write_stream: MemoryObjectSendStream[JSONRPCMessage],
310-
initialization_options: types.InitializationOptions
315+
initialization_options: types.InitializationOptions,
311316
):
312317
with warnings.catch_warnings(record=True) as w:
313-
async with ServerSession(read_stream, write_stream, initialization_options) as session:
318+
async with ServerSession(
319+
read_stream, write_stream, initialization_options
320+
) as session:
314321
async for message in session.incoming_messages:
315322
logger.debug(f"Received message: {message}")
316323

@@ -359,14 +366,16 @@ async def run(
359366

360367
handler = self.notification_handlers[type(notify)]
361368
logger.debug(
362-
f"Dispatching notification of type {type(notify).__name__}"
369+
f"Dispatching notification of type "
370+
f"{type(notify).__name__}"
363371
)
364372

365373
try:
366374
await handler(notify)
367375
except Exception as err:
368376
logger.error(
369-
f"Uncaught exception in notification handler: {err}"
377+
f"Uncaught exception in notification handler: "
378+
f"{err}"
370379
)
371380

372381
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 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

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

@@ -53,7 +54,7 @@ def __init__(
5354
self,
5455
read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
5556
write_stream: MemoryObjectSendStream[JSONRPCMessage],
56-
init_options: InitializationOptions
57+
init_options: InitializationOptions,
5758
) -> None:
5859
super().__init__(read_stream, write_stream, ClientRequest, ClientNotification)
5960
self._initialization_state = InitializationState.NotInitialized
@@ -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

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: 7 additions & 3 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:

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)