The Spanning Tree Protocol (STP) is designed to prevent layer 2 switching loops by automatically disabling redundant links through the Spanning-Tree Algorithm (STA). STP elects a root bridge based on bridge priority and MAC addresses, while also utilizing Bridge Protocol Data Units (BPDUs) to communicate and learn network topology. Additionally, STP defines port roles such as root ports, designated ports, and non-designated ports to manage data flow and maintain a loop-free network topology.