jsonRpcChannel function

StreamChannel<Map<String, Object?>> jsonRpcChannel(
  1. StreamChannel<String> channel
)

Adapts a channel of JSON strings into a channel of decoded JSON-RPC messages.

Each event on channel must contain one complete JSON document; this helper does not provide framing.

Frames which are not valid JSON, or which decode to something other than a JSON object, are answered on channel with a JSON-RPC error response and never surface on the returned channel. This includes JSON-RPC batch frames, which MCP removed in protocol version 2025-06-18.

Implementation

StreamChannel<Map<String, Object?>> jsonRpcChannel(
  StreamChannel<String> channel,
) {
  void answerWithError(int code, String message, Object? request) {
    channel.sink.add(
      jsonEncode(RpcException(code, message).serialize(request)),
    );
  }

  final stream =
      channel.stream
          .map<Object?>(jsonDecode)
          .handleError((Object error, StackTrace stackTrace) {
            if (error is! FormatException) {
              Error.throwWithStackTrace(error, stackTrace);
            }
            answerWithError(
              error_code.PARSE_ERROR,
              'Invalid JSON: ${error.message}',
              error.source,
            );
          }, test: (error) => error is FormatException)
          .where((message) {
            if (message is Map<String, Object?>) return true;
            answerWithError(
              error_code.INVALID_REQUEST,
              message is List
                  ? 'Batch messages are not supported. Batching was removed '
                      'in MCP protocol version 2025-06-18.'
                  : 'Message must be a JSON object.',
              message,
            );
            return false;
          })
          .cast<Map<String, Object?>>();
  final sink = StreamSinkTransformer<Map<String, Object?>, String>.fromHandlers(
    handleData: (data, sink) {
      sink.add(jsonEncode(data));
    },
  ).bind(channel.sink);
  return StreamChannel.withCloseGuarantee(stream, sink);
}