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/
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

Instance Method Summary collapse

Instance Method Details

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



177
178
179
180
181
182
183
# File 'lib/json_rpc_handler.rb', line 177

def error_response(id:, id_validation_pattern:, error:)
  {
    jsonrpc: Version::V2_0,
    id: valid_id?(id, id_validation_pattern) ? id : nil,
    error: error.compact,
  } unless id.nil?
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, &method_finder) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/json_rpc_handler.rb', line 56

def handle_json(request_json, id_validation_pattern: DEFAULT_ALLOWED_ID_CHARACTERS, &method_finder)
  begin
    request = JSON.parse(request_json, symbolize_names: true)
    response = handle(request, id_validation_pattern: id_validation_pattern, &method_finder)
  rescue JSON::ParserError
    response = error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::PARSE_ERROR,
      message: "Parse error",
      data: "Invalid JSON",
    })
  end

  response&.to_json
end

#handle_request_error(error, id, id_validation_pattern) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/json_rpc_handler.rb', line 125

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

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



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/json_rpc_handler.rb', line 71

def process_request(request, id_validation_pattern:, &method_finder)
  id = request[:id]

  error = if !valid_version?(request[:jsonrpc])
    "JSON-RPC version must be 2.0"
  elsif !valid_id?(request[:id], id_validation_pattern)
    "Request ID must match validation pattern, or be an integer or null"
  elsif !valid_method_name?(request[:method])
    'Method name must be a string and not start with "rpc."'
  end

  return error_response(id: :unknown_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 => e
    error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
      code: ErrorCode::INTERNAL_ERROR,
      message: "Internal error",
      data: e.message,
    })
  end
end

#success_response(id:, result:) ⇒ Object



169
170
171
172
173
174
175
# File 'lib/json_rpc_handler.rb', line 169

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)


154
155
156
157
158
159
# File 'lib/json_rpc_handler.rb', line 154

def valid_id?(id, pattern = nil)
  return true if id.nil? || id.is_a?(Integer)
  return false unless id.is_a?(String)

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

#valid_method_name?(method) ⇒ Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/json_rpc_handler.rb', line 161

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

#valid_params?(params) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
# File 'lib/json_rpc_handler.rb', line 165

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

#valid_version?(version) ⇒ Boolean

Returns:

  • (Boolean)


150
151
152
# File 'lib/json_rpc_handler.rb', line 150

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