Class: A2A::Bindings::JsonRpc

Inherits:
Object
  • Object
show all
Defined in:
lib/a2a/bindings/json_rpc.rb

Overview

Rack middleware implementing the A2A JSON-RPC 2.0 protocol binding.

Strips the JSON-RPC envelope from the inbound request, setting env keys for the method name, request id, and parsed params. Calls downstream. On return, wraps env back into a JSON-RPC response envelope.

Streaming operations (SendStreamingMessage, SubscribeToTask): When the handler sets env to an SSE::Stream (which is a Protocol::HTTP::Body::Writable, which is a Readable), Falcon’s protocol-rack passes it through untouched. True async streaming with backpressure — no Thread::Queue, no #each polling.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JsonRpc

Returns a new instance of JsonRpc.



23
24
25
# File 'lib/a2a/bindings/json_rpc.rb', line 23

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



27
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
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/a2a/bindings/json_rpc.rb', line 27

def call(env)
  req  = Rack::Request.new(env)
  body = req.body.read
  req.body.rewind

  begin
    rpc = JSON.parse(body)
  rescue JSON::ParserError
    return error_response(nil, -32700, "Parse error")
  end

  unless rpc.is_a?(Hash) && rpc["jsonrpc"] == "2.0"
    return error_response(nil, -32600, "Invalid Request")
  end

  id     = rpc["id"]
  method = rpc["method"]
  params = rpc["params"] || {}

  env["a2a.json_rpc_id"]     = id
  env["a2a.json_rpc_method"] = method
  env["a2a.body"]            = params

  @app.call(env)

  # Check if handler signalled a JSON-RPC error
  if (err = env["a2a.error"])
    return error_response(id, err[:code], err[:message], err[:data])
  end

  # Check if handler set up a streaming response.
  # The stream is an SSE::Stream (Protocol::HTTP::Body::Readable).
  if (stream = env["a2a.stream"])
    return [200, A2A::SSE::Stream.headers, stream]
  end

  result = env["a2a.result"]
  success_response(id, result)
end