Merge pull request #166 from modelcontextprotocol/davidsp/refactor

refactor: extract request and notification handling
This commit is contained in:
David Soria Parra
2025-01-24 09:54:21 +00:00
committed by GitHub

View File

@@ -433,14 +433,28 @@ class Server:
match message:
case RequestResponder(request=types.ClientRequest(root=req)):
logger.info(
f"Processing request of type {type(req).__name__}"
await self._handle_request(
message, req, session, raise_exceptions
)
case types.ClientNotification(root=notify):
await self._handle_notification(notify)
for warning in w:
logger.info(
f"Warning: {warning.category.__name__}: {warning.message}"
)
async def _handle_request(
self,
message: RequestResponder,
req: Any,
session: ServerSession,
raise_exceptions: bool,
):
logger.info(f"Processing request of type {type(req).__name__}")
if type(req) in self.request_handlers:
handler = self.request_handlers[type(req)]
logger.debug(
f"Dispatching request of type {type(req).__name__}"
)
logger.debug(f"Dispatching request of type {type(req).__name__}")
token = None
try:
@@ -459,9 +473,7 @@ class Server:
except Exception as err:
if raise_exceptions:
raise err
response = types.ErrorData(
code=0, message=str(err), data=None
)
response = types.ErrorData(code=0, message=str(err), data=None)
finally:
# Reset the global state after we are done
if token is not None:
@@ -477,28 +489,20 @@ class Server:
)
logger.debug("Response sent")
case types.ClientNotification(root=notify):
async def _handle_notification(self, notify: Any):
if type(notify) in self.notification_handlers:
assert type(notify) in self.notification_handlers
handler = self.notification_handlers[type(notify)]
logger.debug(
f"Dispatching notification of type "
f"{type(notify).__name__}"
f"Dispatching notification of type " f"{type(notify).__name__}"
)
try:
await handler(notify)
except Exception as err:
logger.error(
f"Uncaught exception in notification handler: "
f"{err}"
)
for warning in w:
logger.info(
f"Warning: {warning.category.__name__}: {warning.message}"
)
logger.error(f"Uncaught exception in notification handler: " f"{err}")
async def _ping_handler(request: types.PingRequest) -> types.ServerResult: