send method

  1. @override
void send(
  1. dynamic message
)
override

Send a message through the transport

Implementation

@override
void send(dynamic message) async {
  if (_isClosed) {
    _logger.debug('Attempted to send on closed authenticated transport');
    return;
  }

  if (_messageEndpoint == null) {
    throw McpError(
      'Cannot send message: Authenticated SSE connection not established',
    );
  }

  try {
    final jsonMessage = jsonEncode(message);
    _logger.debug('Sending authenticated message: $jsonMessage');

    final url = Uri.parse(_messageEndpoint!);
    final client = HttpClient();
    final request = await client.postUrl(url);

    // Set content type
    request.headers.contentType = ContentType.json;

    // Add authentication headers
    _baseHeaders.forEach((name, value) {
      request.headers.add(name, value);
    });

    // Add current OAuth token if available
    if (_oauthToken != null) {
      request.headers.set(
        'Authorization',
        'Bearer ${_oauthToken.accessToken}',
      );
    }

    // Send the request
    request.write(jsonMessage);
    final response = await request.close();

    // Handle response
    if (response.statusCode == 200) {
      final responseBody = await response.transform(utf8.decoder).join();
      _logger.debug(
        'Authenticated message delivery confirmation: $responseBody',
      );
    } else if (response.statusCode == 401 || response.statusCode == 403) {
      final responseBody = await response.transform(utf8.decoder).join();
      _logger.debug(
        'Authentication error during send: ${response.statusCode} - $responseBody',
      );

      // Try to refresh token if possible
      if (_oauthClient != null &&
          _oauthToken?.refreshToken != null &&
          !_isRefreshingToken) {
        await _refreshTokenIfNeeded();
        // Retry the send operation
        return send(message);
      } else {
        throw McpError(
          'Authentication failed during send: ${response.statusCode}',
        );
      }
    } else {
      final responseBody = await response.transform(utf8.decoder).join();
      _logger.debug('Error response: $responseBody');
      throw McpError(
        'Error sending authenticated message: ${response.statusCode}',
      );
    }

    client.close();
    _logger.debug('Authenticated message sent successfully');
  } catch (e) {
    _logger.debug('Error sending authenticated message: $e');
    rethrow;
  }
}