handle method

Future<String> handle(
  1. String requestBody, {
  2. String? authHeader,
})

Handles a raw JSON-RPC request body, returns the JSON-RPC response body.

Implementation

Future<String> handle(String requestBody, {String? authHeader}) async {
  if (token != null && authHeader != 'Bearer $token') {
    return _error(null, -32001, 'unauthorized');
  }
  try {
    final decoded = jsonDecode(requestBody);
    if (decoded is! Map) return _error(null, -32600, 'invalid request');
    final req = decoded.cast<String, dynamic>();
    final id = req['id'];
    final method = req['method'] as String?;
    final params = (req['params'] as Map?)?.cast<String, dynamic>() ?? {};
    final result = switch (method) {
      'message/send' => _handleSend(params),
      'tasks/get' => _handleGet(params),
      'tasks/cancel' => _handleCancel(params),
      _ => throw A2aException('unknown method: $method'),
    };
    return _ok(id, await result);
  } on A2aException catch (e) {
    return _error(null, -32603, e.message);
  } on Object catch (e) {
    return _error(null, -32603, '$e');
  }
}