Merge pull request #324 from koic/ping_client_to_server

Support `ping` client API per MCP specification
This commit is contained in:
Koichi ITO 2026-04-20 12:15:21 +09:00 • committed by GitHub
commit baa093dfd5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -28,6 +28,11 @@ module MCP
end
end
# Raised when a server response fails client-side validation, e.g., a success response
# whose `result` field is missing or has the wrong type. This is distinct from a
# server-returned JSON-RPC error, which is raised as `ServerError`.
class ValidationError < StandardError; end
# Initializes a new MCP::Client instance.
#
# @param transport [Object] The transport object to use for communication with the server.
@ -303,6 +308,24 @@ module MCP
response.dig("result", "completion") || { "values" => [], "hasMore" => false }
end
# Sends a `ping` request to the server to verify the connection is alive.
# Per the MCP spec, the server responds with an empty result.
#
# @return [Hash] An empty hash on success.
# @raise [ServerError] If the server returns a JSON-RPC error.
# @raise [ValidationError] If the response `result` is missing or not a Hash.
#
# @example
# client.ping # => {}
#
# @see https://modelcontextprotocol.io/specification/latest/basic/utilities/ping
def ping
result = request(method: Methods::PING)["result"]
raise ValidationError, "Response validation failed: missing or invalid `result`" unless result.is_a?(Hash)
result
end
private
def request(method:, params: nil)