fix: allow null id in JSONRPCError per JSON-RPC 2.0 spec (#2056)

This commit is contained in:
Max Isbey 2026-02-17 10:30:34 +00:00 • committed by GitHub
commit 705497a593
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 151 additions and 24 deletions

View file

@ -12,7 +12,10 @@ class MCPError(Exception):
def __init__(self, code: int, message: str, data: Any = None):
super().__init__(code, message, data)
self.error = ErrorData(code=code, message=message, data=data)
if data is not None:
self.error = ErrorData(code=code, message=message, data=data)
else:
self.error = ErrorData(code=code, message=message)
@property
def code(self) -> int:

View file

@ -142,7 +142,7 @@ class RequestResponder(Generic[ReceiveRequestT, SendResultT]):
# Send an error response to indicate cancellation
await self._session._send_response( # type: ignore[reportPrivateUsage]
request_id=self.request_id,
response=ErrorData(code=0, message="Request cancelled", data=None),
response=ErrorData(code=0, message="Request cancelled"),
)
@property
@ -458,6 +458,12 @@ class BaseSession(
if not isinstance(message.message, JSONRPCResponse | JSONRPCError):
return # pragma: no cover
if message.message.id is None:
# Narrows to JSONRPCError since JSONRPCResponse.id is always RequestId
error = message.message.error
logging.warning(f"Received error with null ID: {error.message}")
await self._handle_incoming(MCPError(error.code, error.message, error.data))
return
# Normalize response ID to handle type mismatches (e.g., "0" vs 0)
response_id = self._normalize_request_id(message.message.id)