Module: JsonRpcHandler

Extended by:
JsonRpcHandler
Included in:
JsonRpcHandler
Defined in:
lib/json_rpc_handler.rb

Defined Under Namespace

Classes: ErrorCode, Version

Constant Summary collapse

DEFAULT_ALLOWED_ID_CHARACTERS =
/\A[a-zA-Z0-9_-]+\z/.freeze
NO_RESPONSE =

Sentinel return value from a handler. When a handler returns this, process_request emits no JSON-RPC response for the request, matching the notification-style semantics (id is ignored).

Object.new.freeze
MAX_INTEGER_ID_BITS =

An integer id is written back into the response, and writing an integer out in decimal takes time that grows faster than its length: one of a few million digits, which fits in a request body, costs a minute of CPU. 128 bits leaves room for any counter and for a UUID carried as a number.

128

Instance Method Summary collapse

Instance Method Details

#encodable_response(response, id_validation_pattern: nil) ⇒ Object

response with each part JSON cannot generate replaced with Internal error. A batch is replaced item by item, so the other items keep their results.



92
93
94
95
96
97
98
99
# File 'lib/json_rpc_handler.rb', line 92

def encodable_response(response, id_validation_pattern: nil)
  return response.map { |item| encodable_response(item, id_validation_pattern: id_validation_pattern) } if response.is_a?(Array)

  response.to_json
  response
rescue JSON::GeneratorError
  internal_error_for(response, id_validation_pattern: id_validation_pattern)
end

#error_response(id:, id_validation_pattern:, error:) ⇒ Object

An error response for a request whose id could not be read carries no id member: JSON-RPC 2.0 puts a null there, but the MCP schema allows only a string or an integer, and the Streamable HTTP transport specification describes such a body as an error response that has no id.



260
261
262
263
264
265
266
267
# File 'lib/json_rpc_handler.rb', line 260

def error_response(id:, id_validation_pattern:, error:)
  return if id.nil?

  response = { jsonrpc: Version::V2_0 }
  response[:id] = id if valid_id?(id, id_validation_pattern)
  response[:error] = error.compact
  response
end

#handle(request, id_validation_pattern: DEFAULT_ALLOWED_ID_CHARACTERS, &method_finder) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/json_rpc_handler.rb', line 28

def handle(request, id_validation_pattern: DEFAULT_ALLOWED_ID_CHARACTERS, &method_finder)
  if request.is_a?(Array)
    return error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INVALID_REQUEST,
      message: "Invalid Request",
      data: "Request is an empty array",
    }) if request.empty?

    # Handle batch requests
    responses = request.map { |req| process_request(req, id_validation_pattern: id_validation_pattern, &method_finder) }.compact

    # A single item is hoisted out of the array
    return responses.first if responses.one?

    # An empty array yields nil
    responses if responses.any?
  elsif request.is_a?(Hash)
    # Handle single request
    process_request(request, id_validation_pattern: id_validation_pattern, &method_finder)
  else
    error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INVALID_REQUEST,
      message: "Invalid Request",
      data: "Request must be an array or a hash",
    })
  end
end

#handle_json(request_json, id_validation_pattern: DEFAULT_ALLOWED_ID_CHARACTERS, on_generate_error: nil, &method_finder) ⇒ Object

on_generate_error, when given, is called with the JSON::GeneratorError of a response that cannot be generated, before that response is replaced with Internal error.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/json_rpc_handler.rb', line 58

def handle_json(request_json, id_validation_pattern: DEFAULT_ALLOWED_ID_CHARACTERS, on_generate_error: nil, &method_finder)
  begin
    begin
      request = JSON.parse(request_json, symbolize_names: true)
    rescue JSON::ParserError, EncodingError
      # `symbolize_names` raises `EncodingError` for a key that is not valid UTF-8, a parse error as well.
      # Rescued around the parse only, so an error raised while handling keeps its own classification.
      return error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
        code: ErrorCode::PARSE_ERROR,
        message: "Parse error",
        data: "Invalid JSON",
      }).to_json
    end

    response = handle(request, id_validation_pattern: id_validation_pattern, &method_finder)
  rescue StandardError
    # Last-resort guard so an unexpected handling error returns a JSON-RPC error
    # instead of escaping to the transport loop.
    response = error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INTERNAL_ERROR,
      message: "Internal error",
    })
  end

  begin
    response&.to_json
  rescue JSON::GeneratorError => e
    on_generate_error&.call(e)
    encodable_response(response, id_validation_pattern: id_validation_pattern).to_json
  end
end

#handle_request_error(error, id, id_validation_pattern) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/json_rpc_handler.rb', line 193

def handle_request_error(error, id, id_validation_pattern)
  if error.respond_to?(:error_code) && error.error_code
    code = error.error_code
    message = error.message
  else
    error_type = error.respond_to?(:error_type) ? error.error_type : nil

    code, message = case error_type
    when :invalid_request then [ErrorCode::INVALID_REQUEST, "Invalid Request"]
    when :invalid_params then [ErrorCode::INVALID_PARAMS, "Invalid params"]
    when :parse_error then [ErrorCode::PARSE_ERROR, "Parse error"]
    when :internal_error then [ErrorCode::INTERNAL_ERROR, "Internal error"]
    else [ErrorCode::INTERNAL_ERROR, "Internal error"]
    end
  end

  data = error.respond_to?(:error_data) && error.error_data ? error.error_data : error.message

  error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
    code: code,
    message: message,
    data: data,
  })
end

#internal_error_for(response, id_validation_pattern: nil) ⇒ Object

The error answering a request whose response cannot be generated: a result or an error holding a string that is not valid UTF-8, typically one the request carried and the SDK or a handler repeated, such as a tool name in its Tool not found error. It carries the request id when the response has one, which was validated before the method ran.



105
106
107
108
109
110
111
# File 'lib/json_rpc_handler.rb', line 105

def internal_error_for(response, id_validation_pattern: nil)
  id = response[:id] if response.is_a?(Hash)
  error_response(id: id.nil? ? :unknown_id : id, id_validation_pattern: id_validation_pattern, error: {
    code: ErrorCode::INTERNAL_ERROR,
    message: "Internal error",
  })
end

#oversized_integer_id?(id) ⇒ Boolean

Returns:

  • (Boolean)


227
228
229
# File 'lib/json_rpc_handler.rb', line 227

def oversized_integer_id?(id)
  id.is_a?(Integer) && id.bit_length > MAX_INTEGER_ID_BITS
end

#process_request(request, id_validation_pattern:, &method_finder) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/json_rpc_handler.rb', line 113

def process_request(request, id_validation_pattern:, &method_finder)
  # A batch element can be any JSON value; a non-object element cannot carry an id or a method,
  # so reject it before the `request[:id]` access below.
  unless request.is_a?(Hash)
    return error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INVALID_REQUEST,
      message: "Invalid Request",
      data: "Request must be an object",
    })
  end

  id = request[:id]

  error = if !valid_version?(request[:jsonrpc])
    "JSON-RPC version must be 2.0"
  elsif request.key?(:id) && id.nil?
    # JSON-RPC 2.0 allows a null id; MCP rules it out: a request carries a string or an integer id,
    # and a notification carries no id member at all. Refused rather than run as a notification,
    # since a sender that wrote an id meant to be answered.
    "Request ID must not be null"
  elsif oversized_integer_id?(id)
    "Request ID must be an integer of at most #{MAX_INTEGER_ID_BITS} bits"
  elsif !valid_id?(id, id_validation_pattern)
    if id_validation_pattern
      "Request ID must be a string matching the validation pattern, or an integer"
    else
      "Request ID must be a string or an integer"
    end
  elsif !valid_method_name?(request[:method])
    'Method name must be a string and not start with "rpc."'
  end

  # Per JSON-RPC 2.0 (Response object, `id`), the error response must carry
  # the same id as the request when the id could be detected. `error_response`
  # leaves the id out for ids that fail validation, and the `:unknown_id` sentinel
  # keeps a response (without an id) being emitted when the request carried no id at all.
  return error_response(id: id.nil? ? :unknown_id : id, id_validation_pattern: id_validation_pattern, error: {
    code: ErrorCode::INVALID_REQUEST,
    message: "Invalid Request",
    data: error,
  }) if error

  method_name = request[:method]
  params = request[:params]

  unless valid_params?(params)
    return error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INVALID_PARAMS,
      message: "Invalid params",
      data: "Method parameters must be an array or an object or null",
    })
  end

  begin
    method = method_finder.call(method_name, id)

    if method.nil?
      return error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
        code: ErrorCode::METHOD_NOT_FOUND,
        message: "Method not found",
        data: method_name,
      })
    end

    result = method.call(params)
    return if result.equal?(NO_RESPONSE)

    success_response(id: id, result: result)
  rescue MCP::Server::RequestHandlerError => e
    handle_request_error(e, id, id_validation_pattern)
  rescue StandardError
    # The exception message is deliberately not echoed into `data`: it can carry
    # internals that must not reach untrusted clients (CWE-209).
    error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INTERNAL_ERROR,
      message: "Internal error",
    })
  end
end

#success_response(id:, result:) ⇒ Object



249
250
251
252
253
254
255
# File 'lib/json_rpc_handler.rb', line 249

def success_response(id:, result:)
  {
    jsonrpc: Version::V2_0,
    id: id,
    result: result,
  } unless id.nil?
end

#valid_id?(id, pattern = nil) ⇒ Boolean

Returns:

  • (Boolean)


231
232
233
234
235
236
237
238
239
# File 'lib/json_rpc_handler.rb', line 231

def valid_id?(id, pattern = nil)
  return true if id.nil?
  return !oversized_integer_id?(id) if id.is_a?(Integer)
  # A string that is not valid in its encoding cannot be written into the response,
  # and matching a pattern against it raises, so it is refused before the method runs.
  return false unless id.is_a?(String) && id.valid_encoding?

  pattern ? id.match?(pattern) : true
end

#valid_method_name?(method) ⇒ Boolean

Returns:

  • (Boolean)


241
242
243
# File 'lib/json_rpc_handler.rb', line 241

def valid_method_name?(method)
  method.is_a?(String) && method.valid_encoding? && !method.start_with?("rpc.")
end

#valid_params?(params) ⇒ Boolean

Returns:

  • (Boolean)


245
246
247
# File 'lib/json_rpc_handler.rb', line 245

def valid_params?(params)
  params.nil? || params.is_a?(Array) || params.is_a?(Hash)
end

#valid_version?(version) ⇒ Boolean

Returns:

  • (Boolean)


218
219
220
# File 'lib/json_rpc_handler.rb', line 218

def valid_version?(version)
  version == Version::V2_0
end