Class: A2A::Server::Bindings::JsonRpc

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

Overview

Claims requests under its path prefix (default "/", i.e. everything) that were not already claimed by a binding earlier in the stack (env unset); all other requests pass through untouched.

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, path_prefix: "/") ⇒ JsonRpc

Returns a new instance of JsonRpc.



28
29
30
31
# File 'lib/a2a/server/bindings/json_rpc.rb', line 28

def initialize(app, path_prefix: "/")
  @app = app
  @path_prefix = path_prefix
end

Instance Method Details

#call(env) ⇒ Object



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
66
67
68
69
70
71
72
73
74
# File 'lib/a2a/server/bindings/json_rpc.rb', line 33

def call(env)
  return @app.call(env) if env.key?("a2a.body")

  req = Rack::Request.new(env)
  return @app.call(env) unless claims?(req.path_info)

  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

  result = @app.call(env)

  # Check if the result is an error object
  if result.is_a?(A2A::Error)
    return error_response(id, result.code, result.message, result.error_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::Server::SSE::Stream.headers, stream]
  end

  success_response(id, result)
end