How to enable undo for operators in sculpt mode?
As a variant of a solution. I could suggest adding history before all the code. But I'm pretty sure this is a bug in Blender's sculpt mode.
if context.mode != 'OBJECT':    
    bpy.ops.ed.undo_push()