Class: A2A::Rails::A2aController

Inherits:
ApplicationController
  • Object
show all
Includes:
ControllerHelpers, Utils::RailsDetection
Defined in:
lib/a2a/rails/a2a_controller.rb

Instance Method Summary collapse

Methods included from Utils::RailsDetection

#rails_application, #rails_available?, #rails_development?, #rails_environment, #rails_logger, #rails_production?, #rails_version, #rails_version_requires_validation?, #rails_version_supported?

Methods included from ControllerHelpers

#a2a_request?, #agent_card_url, #api_key_authenticated?, #authenticate_a2a_request, #build_a2a_error_response, #build_additional_interfaces, #build_agent_metadata, #build_provider_info, #build_security_config, #collect_capabilities_hash, #collect_skills, #current_user_authenticated?, #current_user_info, #current_user_permissions, #current_user_roles, #documentation_url, #enhance_authenticated_card, #generate_agent_card, #grpc_endpoint_url, #grpc_port, #handle_a2a_error, #handle_a2a_rpc, #handle_authentication_error, #handle_single_a2a_request, #handle_task_not_found, #http_json_endpoint_url, #jwt_authenticated?, #method_requires_authentication?, #render_agent_card, #set_a2a_headers, #supports_authenticated_card?

Instance Method Details

#agent_cardObject

Serve agent card



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/a2a/rails/a2a_controller.rb', line 44

def agent_card
  card = generate_agent_card

  # Support different output formats
  case request.format.symbol
  when :json
    render json: card.to_h
  when :jws
    # TODO: Implement JWS signing
    render json: { error: "JWS format not yet implemented" }, status: :not_implemented
  else
    render json: card.to_h
  end
rescue StandardError => e
  render json: { error: e.message }, status: :internal_server_error
end

#authenticated?Boolean (private)

Returns:

  • (Boolean)


216
217
218
219
220
221
# File 'lib/a2a/rails/a2a_controller.rb', line 216

def authenticated?
  # Check if request is authenticated
  # This can be overridden by applications to integrate with their auth system
  request.headers["Authorization"].present? ||
    (respond_to?(:current_user) && current_user.present?)
end

#authenticated_agent_cardObject

Serve authenticated agent card



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/a2a/rails/a2a_controller.rb', line 62

def authenticated_agent_card
  # Ensure authentication is present
  unless authenticated?
    render json: { error: "Authentication required" }, status: :unauthorized
    return
  end

  card = generate_authenticated_agent_card
  render json: card.to_h
rescue StandardError => e
  render json: { error: e.message }, status: :internal_server_error
end

#build_error_response(error, id = nil) ⇒ Object (private)



183
184
185
186
187
188
# File 'lib/a2a/rails/a2a_controller.rb', line 183

def build_error_response(error, id = nil)
  A2A::Protocol::JsonRpc.build_response(
    error: error.to_json_rpc_error,
    id: id
  )
end

#capabilitiesObject

List capabilities



76
77
78
79
80
81
# File 'lib/a2a/rails/a2a_controller.rb', line 76

def capabilities
  capabilities = collect_capabilities
  render json: { capabilities: capabilities }
rescue StandardError => e
  render json: { error: e.message }, status: :internal_server_error
end

#collect_capabilitiesObject (private)



202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/a2a/rails/a2a_controller.rb', line 202

def collect_capabilities
  # Collect all registered A2A capabilities from controllers
  capabilities = []

  # Scan all controllers that include A2A::Server::Agent
  ObjectSpace.each_object(Class) do |klass|
    if klass < ActionController::Base && klass.included_modules.include?(A2A::Server::Agent)
      capabilities.concat(klass._a2a_capabilities || [])
    end
  end

  capabilities.map(&:to_h)
end

#generate_authenticated_agent_cardObject (private)



190
191
192
193
194
195
196
197
198
199
200
# File 'lib/a2a/rails/a2a_controller.rb', line 190

def generate_authenticated_agent_card
  # Generate extended agent card with authentication context
  card = generate_agent_card

  # Add authenticated-specific information
  card_hash = card.to_h
  card_hash[:authenticated_user] =  if respond_to?(:current_user_info)
  card_hash[:permissions] = current_user_permissions if respond_to?(:current_user_permissions)

  A2A::Types::AgentCard.from_h(card_hash)
end

#handle_single_request(json_rpc_request) ⇒ Object (private)



173
174
175
176
177
178
179
180
181
# File 'lib/a2a/rails/a2a_controller.rb', line 173

def handle_single_request(json_rpc_request)
  # Delegate to the A2A request handler
  handle_a2a_request(json_rpc_request)
rescue A2A::Errors::A2AError => e
  build_error_response(e, json_rpc_request.id)
rescue StandardError => e
  error = A2A::Errors::InternalError.new(e.message)
  build_error_response(error, json_rpc_request.id)
end

#handle_task_artifact_webhook(task_id, payload) ⇒ Object (private)



248
249
250
251
252
253
254
255
# File 'lib/a2a/rails/a2a_controller.rb', line 248

def handle_task_artifact_webhook(task_id, payload)
  # Process task artifact update webhook
  artifact_data = payload["artifact"]
  artifact = A2A::Types::Artifact.from_h(artifact_data)
  append = payload["append"] || false

  A2A::Server::TaskManager.instance.update_task_artifact(task_id, artifact, append: append)
end

#handle_task_status_webhook(task_id, payload) ⇒ Object (private)



240
241
242
243
244
245
246
# File 'lib/a2a/rails/a2a_controller.rb', line 240

def handle_task_status_webhook(task_id, payload)
  # Process task status update webhook
  status_data = payload["status"]
  status = A2A::Types::TaskStatus.from_h(status_data)

  A2A::Server::TaskManager.instance.update_task_status(task_id, status)
end

#healthObject

Health check endpoint



84
85
86
87
88
89
90
91
# File 'lib/a2a/rails/a2a_controller.rb', line 84

def health
  render json: {
    status: "healthy",
    version: A2A::VERSION,
    timestamp: Time.now.iso8601,
    rails_version: rails_version || "unknown"
  }
end

#rpcObject

Handle JSON-RPC requests



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/a2a/rails/a2a_controller.rb', line 21

def rpc
  request_body = request.body.read

  begin
    json_rpc_request = A2A::Protocol::JsonRpc.parse_request(request_body)

    # Handle batch requests
    if json_rpc_request.is_a?(Array)
      responses = json_rpc_request.map { |req| handle_single_request(req) }
      render json: responses
    else
      response = handle_single_request(json_rpc_request)
      render json: response
    end
  rescue A2A::Errors::A2AError => e
    render json: build_error_response(e), status: :bad_request
  rescue StandardError => e
    error = A2A::Errors::InternalError.new(e.message)
    render json: build_error_response(error), status: :internal_server_error
  end
end

#streamObject

Server-Sent Events streaming endpoint



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
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/a2a/rails/a2a_controller.rb', line 94

def stream
  task_id = params[:task_id]

  begin
    task = A2A::Server::TaskManager.instance.get_task(task_id)

    response.headers["Content-Type"] = "text/event-stream"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Connection"] = "keep-alive"

    # Set up SSE stream
    sse = A2A::Transport::SSE.new(response.stream)

    # Send initial task status
    sse.write_event("task-status", task.to_h)

    # Subscribe to task updates
    subscription = A2A::Server::TaskManager.instance.subscribe_to_task(task_id) do |event|
      case event
      when A2A::Types::TaskStatusUpdateEvent
        sse.write_event("task-status-update", event.to_h)
      when A2A::Types::TaskArtifactUpdateEvent
        sse.write_event("task-artifact-update", event.to_h)
      end
    end

    # Keep connection alive until client disconnects
    loop do
      break if response.stream.closed?

      sleep 1
      sse.write_event("heartbeat", { timestamp: Time.now.iso8601 })
    end
  rescue A2A::Errors::TaskNotFound
    render json: { error: "Task not found" }, status: :not_found
  rescue StandardError => e
    render json: { error: e.message }, status: :internal_server_error
  ensure
    subscription&.unsubscribe
    response.stream.close
  end
end

#verify_webhook_authentication!Object (private)



227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/a2a/rails/a2a_controller.rb', line 227

def verify_webhook_authentication!
  # Verify webhook signature or token
  # This should be implemented based on the specific authentication method
  auth_header = request.headers["Authorization"]

  return if auth_header.present?

  raise A2A::Errors::AuthenticationError, "Missing webhook authentication"

  # TODO: Implement specific webhook authentication logic
  # This could verify HMAC signatures, JWT tokens, etc.
end

#webhookObject

Webhook endpoint for push notifications



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
# File 'lib/a2a/rails/a2a_controller.rb', line 138

def webhook
  task_id = params[:task_id]

  begin
    # Verify webhook authentication if configured
    verify_webhook_authentication! if webhook_authentication_required?

    # Process webhook payload
    payload = JSON.parse(request.body.read)

    # Handle different webhook types
    case payload["type"]
    when "task_status_update"
      handle_task_status_webhook(task_id, payload)
    when "task_artifact_update"
      handle_task_artifact_webhook(task_id, payload)
    else
      render json: { error: "Unknown webhook type" }, status: :bad_request
      return
    end

    render json: { status: "processed" }
  rescue JSON::ParserError
    render json: { error: "Invalid JSON payload" }, status: :bad_request
  rescue A2A::Errors::TaskNotFound
    render json: { error: "Task not found" }, status: :not_found
  rescue A2A::Errors::AuthenticationError
    render json: { error: "Webhook authentication failed" }, status: :unauthorized
  rescue StandardError => e
    render json: { error: e.message }, status: :internal_server_error
  end
end

#webhook_authentication_required?Boolean (private)

Returns:

  • (Boolean)


223
224
225
# File 'lib/a2a/rails/a2a_controller.rb', line 223

def webhook_authentication_required?
  A2A.config.webhook_authentication_required || false
end