Fix an incorrect result: null response to an id-bearing notification message

## Motivation and Context

A JSON-RPC notification carries no id and must not receive any response.
When a client erroneously sent a notification-only method such as `notifications/cancelled` with an id,
the server replied with a successful `result: null`, which is neither a valid MCP result nor
a legal reply to a notification.

Such a message is now treated as a request for a method that has no request handler and rejected with
Method not found, matching the behavior of the TypeScript and Python SDKs. A well-formed notification
that omits the id continues to receive no response.

Fixes #434.

## How Has This Been Tested?

Added regression tests covering id-bearing `notifications/cancelled`, `notifications/initialized`,
and `notifications/progress`, a batch that mixes an id-bearing notification with other messages,
custom `notifications/*` methods, and the same case over the HTTP transport.

## Breaking Changes

None for spec-conformant clients, which never put an id on a notification.
The only behavioral change is that a malformed id-bearing notification now receives a Method not found error
instead of a spurious `result: null`.
This commit is contained in:
Koichi ITO 2026-07-01 01:30:56 +09:00
commit 6d42cf7826
2 changed files with 133 additions and 0 deletions

View file

@ -47,6 +47,10 @@ module MCP
end
class << self
def notification?(method)
method.is_a?(String) && method.start_with?("notifications/")
end
def ensure_capability!(method, capabilities)
case method
when PROMPTS_GET, PROMPTS_LIST

View file

@ -423,6 +423,13 @@ module MCP
end
def handle_request(request, method, session: nil, related_request_id: nil)
# A well-formed notification carries no JSON-RPC id and receives no response.
# If a client erroneously sends a notification-only method with an id, the message
# is framed as a request; since notification methods have no request handler,
# returning `nil` here makes `JsonRpcHandler` report "Method not found", matching
# the TypeScript and Python SDKs rather than emitting a spurious `result: null`.
return if Methods.notification?(method) && !related_request_id.nil?
# `notifications/cancelled` is dispatched directly: it is a notification (no JSON-RPC id)
# and intentionally bypasses the `@handlers` lookup, capability check, in-flight registry,
# and rescue blocks below.