I expect you need to filter for specifically autopilot heartbeats - otherwise every time it detects a different type of heartbeat it will internally change which options are available, and error out if you try to perform some unsupported operation for that component.
I’m not certain what’s happening there, but depending on how+where you’re running your code you may be preventing BlueOS from opening one of its MAVLink Endpoints, or you could be running some alternative server (perhaps in an extension) that is using a port it’s trying to make use of, so there’s a conflict when it tries to open a MAVLink connection there.