This paper aims to provide the smart grid research community with an open and accessible general mathematical framework to develop and implement optimal flexibility mechanisms in large-scale network applications. The motivation of this paper is twofold. On the one hand, flexibility mechanisms are currently a hot topic of research, which is aimed to mitigate variation and uncertainty of electricity demand and supply in decentralised grids with a high aggregated share of renewables. On the other hand, a large part of such related research is performed by heuristic methods, which are generally inefficient (such methods do not guarantee optimality) and difficult to extrapolate for different use cases. Alternatively, this paper presents an MPC-based (Model Predictive Control) framework explicitly including a generic flexibility mechanism which is easy to particularise to specific strategies such as Demand Response, Flexible Production and Energy Efficiency Services. The proposed framework is benchmarked with other non-optimal control configurations to better show the advantages it provides. The work of this paper is completed by the implementation of a generic use case which aims to further clarify the use of the framework and thus, to ease its adoption by other researchers in their specific flexibility mechanisms applications.