Skip to content

Commit bfe9537

Browse files
committed
refactor: use dict instead of list of tuples for handler maps
1 parent 7e9e53f commit bfe9537

File tree

1 file changed

+30
-28
lines changed

1 file changed

+30
-28
lines changed

src/mcp/server/lowlevel/server.py

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -204,39 +204,41 @@ def __init__(
204204
logger.debug("Initializing server %r", name)
205205

206206
# Populate internal handler dicts from on_* kwargs
207-
_request_handler_map: list[
208-
tuple[str, Callable[[ServerRequestContext[LifespanResultT, Any], Any], Awaitable[Any]] | None]
209-
] = [
210-
("ping", on_ping),
211-
("prompts/list", on_list_prompts),
212-
("prompts/get", on_get_prompt),
213-
("resources/list", on_list_resources),
214-
("resources/templates/list", on_list_resource_templates),
215-
("resources/read", on_read_resource),
216-
("resources/subscribe", on_subscribe_resource),
217-
("resources/unsubscribe", on_unsubscribe_resource),
218-
("tools/list", on_list_tools),
219-
("tools/call", on_call_tool),
220-
("logging/setLevel", on_set_logging_level),
221-
("completion/complete", on_completion),
222-
]
223-
for method, handler in _request_handler_map:
224-
if handler is not None:
225-
self._request_handlers[method] = handler
207+
self._request_handlers.update(
208+
{
209+
method: handler
210+
for method, handler in {
211+
"ping": on_ping,
212+
"prompts/list": on_list_prompts,
213+
"prompts/get": on_get_prompt,
214+
"resources/list": on_list_resources,
215+
"resources/templates/list": on_list_resource_templates,
216+
"resources/read": on_read_resource,
217+
"resources/subscribe": on_subscribe_resource,
218+
"resources/unsubscribe": on_unsubscribe_resource,
219+
"tools/list": on_list_tools,
220+
"tools/call": on_call_tool,
221+
"logging/setLevel": on_set_logging_level,
222+
"completion/complete": on_completion,
223+
}.items()
224+
if handler is not None
225+
}
226+
)
226227

227228
# Default ping handler if not provided
228229
if "ping" not in self._request_handlers:
229230
self._request_handlers["ping"] = _ping_handler
230231

231-
_notification_handler_map: list[
232-
tuple[str, Callable[[ServerRequestContext[LifespanResultT, Any], Any], Awaitable[None]] | None]
233-
] = [
234-
("notifications/roots/list_changed", on_roots_list_changed),
235-
("notifications/progress", on_progress),
236-
]
237-
for method, handler in _notification_handler_map:
238-
if handler is not None:
239-
self._notification_handlers[method] = handler
232+
self._notification_handlers.update(
233+
{
234+
method: handler
235+
for method, handler in {
236+
"notifications/roots/list_changed": on_roots_list_changed,
237+
"notifications/progress": on_progress,
238+
}.items()
239+
if handler is not None
240+
}
241+
)
240242

241243
def _add_request_handler(
242244
self,

0 commit comments

Comments
 (0)