Module: Tina4::McpProtocol

Defined in:
lib/tina4/mcp.rb

Overview

── JSON-RPC 2.0 codec ────────────────────────────────────────────

Constant Summary collapse

PARSE_ERROR =

Standard JSON-RPC 2.0 error codes

-32_700
INVALID_REQUEST =
-32_600
METHOD_NOT_FOUND =
-32_601
INVALID_PARAMS =
-32_602
INTERNAL_ERROR =
-32_603

Class Method Summary collapse

Class Method Details

.decode_request(data) ⇒ Array<(String, Hash, Object)>

Decode a JSON-RPC 2.0 request.

Returns:

  • (Array<(String, Hash, Object)>)

    method, params, request_id

Raises:

  • (ArgumentError)

    if the message is malformed



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/tina4/mcp.rb', line 66

def self.decode_request(data)
  case data
  when String
    begin
      msg = JSON.parse(data)
    rescue JSON::ParserError => e
      raise ArgumentError, "Invalid JSON: #{e.message}"
    end
  when Hash
    msg = data
  else
    raise ArgumentError, "Message must be a String or Hash"
  end

  raise ArgumentError, "Message must be a JSON object" unless msg.is_a?(Hash)
  raise ArgumentError, "Missing or invalid jsonrpc version" unless msg["jsonrpc"] == "2.0"

  method = msg["method"]
  raise ArgumentError, "Missing or invalid method" if method.nil? || !method.is_a?(String) || method.empty?

  params     = msg.fetch("params", {})
  request_id = msg["id"] # nil for notifications

  [method, params, request_id]
end

.encode_error(request_id, code, message, data = nil) ⇒ Object

Encode a JSON-RPC 2.0 error response.



45
46
47
48
49
50
51
52
53
# File 'lib/tina4/mcp.rb', line 45

def self.encode_error(request_id, code, message, data = nil)
  error = { "code" => code, "message" => message }
  error["data"] = data unless data.nil?
  JSON.generate({
    "jsonrpc" => "2.0",
    "id"      => request_id,
    "error"   => error
  })
end

.encode_notification(method, params = nil) ⇒ Object

Encode a JSON-RPC 2.0 notification (no id).



56
57
58
59
60
# File 'lib/tina4/mcp.rb', line 56

def self.encode_notification(method, params = nil)
  msg = { "jsonrpc" => "2.0", "method" => method }
  msg["params"] = params unless params.nil?
  JSON.generate(msg)
end

.encode_response(request_id, result) ⇒ Object

Encode a successful JSON-RPC 2.0 response.



36
37
38
39
40
41
42
# File 'lib/tina4/mcp.rb', line 36

def self.encode_response(request_id, result)
  JSON.generate({
    "jsonrpc" => "2.0",
    "id"      => request_id,
    "result"  => result
  })
end