Skip to content

Commit c583fb6

Browse files
committed
refactor: replace assert with natural type narrowing for null-id check
Restructure the null-id guard so that `id is None` is checked first, allowing Pyright to naturally narrow the type to JSONRPCError (since JSONRPCResponse.id is always RequestId). This eliminates the need for the assert that was previously required to work around Pyright's inability to narrow through negated compound conditions.
1 parent bf35f27 commit c583fb6

File tree

1 file changed

+2
-9
lines changed

1 file changed

+2
-9
lines changed

src/mcp/shared/session.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -458,19 +458,12 @@ async def _handle_response(self, message: SessionMessage) -> None:
458458
if not isinstance(message.message, JSONRPCResponse | JSONRPCError):
459459
return # pragma: no cover
460460

461-
# Handle null-id errors (e.g., parse errors, invalid requests) before
462-
# routing. Per JSON-RPC 2.0, id is null when the request id could not
463-
# be determined — these cannot be correlated to any pending request.
464-
if isinstance(message.message, JSONRPCError) and message.message.id is None:
461+
if message.message.id is None:
462+
# Narrows to JSONRPCError since JSONRPCResponse.id is always RequestId
465463
error = message.message.error
466464
logging.warning(f"Received error with null ID: {error.message}")
467465
await self._handle_incoming(MCPError(error.code, error.message, error.data))
468466
return
469-
470-
# After the null-id guard above, id is guaranteed to be non-None.
471-
# JSONRPCResponse.id is always RequestId, and JSONRPCError.id is only
472-
# None for parse errors (handled above).
473-
assert message.message.id is not None
474467
# Normalize response ID to handle type mismatches (e.g., "0" vs 0)
475468
response_id = self._normalize_request_id(message.message.id)
476469

0 commit comments

Comments
 (0)