streamableHttpClientChannel function

StreamChannel<Map<String, Object?>> streamableHttpClientChannel(
  1. Uri uri, {
  2. required ProtocolVersion protocolVersion,
  3. required ClientCapabilities clientCapabilities,
  4. Implementation? clientInfo,
  5. Map<String, String>? headers,
})

Creates a StreamChannel that POSTs each JSON-RPC message to uri.

protocolVersion must have ProtocolVersion.supportsStreamableHttp and is written to _meta and MCP-Protocol-Version. clientCapabilities and clientInfo merge into _meta. JSON replies use jsonDecode and SSE replies use sseMessageStream. A failed POST is a JSON-RPC error for that request ID, or an error on the channel itself when it carried a notification. Notifications have no ID to carry an error. A response stream that ends without answering the request fails it the same way. A 202 on a notification is not an inbound message. Valid x-mcp-header annotations from tools/list are mirrored on later tools/call requests. Invalid tool definitions are dropped. The headers map is written to each POST, and the protocol's own headers override it. Does not send initialize.

Implementation

StreamChannel<Map<String, Object?>> streamableHttpClientChannel(
  Uri uri, {
  required ProtocolVersion protocolVersion,
  required ClientCapabilities clientCapabilities,
  Implementation? clientInfo,
  Map<String, String>? headers,
}) {
  if (!protocolVersion.supportsStreamableHttp) {
    final supportedVersions = ProtocolVersion.values
        .where((version) => version.supportsStreamableHttp)
        .map((version) => version.versionString)
        .join(', ');
    throw ArgumentError.value(
      protocolVersion.versionString,
      Keys.protocolVersion,
      'The Streamable HTTP client channel only allows one of: '
      '$supportedVersions',
    );
  }
  // Reject a bad identifier when the channel opens instead of on the first
  // request. This checks and returns, so the caller keeps the object each
  // message forwards and a capability set later still reaches the server.
  ClientCapabilities.fromMap(clientCapabilities as Map<String, Object?>);

  final controller = StreamChannelController<Map<String, Object?>>();
  final httpClient = HttpClient();
  final state = _StreamableHttpClientState();
  controller.local.stream
      .tap(null, onDone: () => httpClient.close(force: true))
      .concurrentAsyncExpand(
        (message) => _sendStreamableHttpMessage(
          httpClient,
          uri,
          message,
          protocolVersion,
          clientCapabilities,
          clientInfo,
          headers,
          state,
        ),
      )
      .listen(
        controller.local.sink.add,
        onError: controller.local.sink.addError,
        onDone: controller.local.sink.close,
      );
  return _StreamableHttpClientChannel(controller.foreign, state);
}