To ensure the continuous operation of a microgrid, proactive planning is essential, especially when contemplating possible dynamic events that alter the scheduled scenarios for the islanded operation or during its transition from connected to islanded mode. This paper introduces an innovative mathematical programming model for the AC optimal power flow (AC-OPF) with dynamic security constraints (DSCs), considering two scenarios: the islanded operation and the transition. This model uses positive-sequence equations to represent the inverter-based resources (IBRs) for grid-forming and grid-following roles, along with a fourth-order synchronous generator model equipped with excitation and frequency control systems. They assess the dynamic response to specific events such as short-circuits, decreases in PV generation, increases in load demand during the islanded operation, and the transition itself. The DSCs are applied to dispatchable distributed energy resources (DERs), which react to variations in the microgrid, considering generation and opportunity costs to minimize the discrepancy between planned and secure operating points. The mathematical programming model is implemented using AMPL, and solutions are obtained through the nonlinear optimization solver IPOPT. The tests are conducted in an adapted version of the microgrid being developed at the University of Campinas that includes a synchronous generator, photovoltaic (PV) generation, and a battery energy storage system (BESS). Results demonstrate the model’s effectiveness in adjusting generation dispatch to withstand defined events and optimizing generation resources, even when limits are not reached.