Triggering actions using OSC messages

I’m wondering whether it is possible to have an osc server which can trigger actions.

For example, if I send /bar to the following .lua script, it prints a message ok.
But if I want to run a vim.cmd(), it gives an error.

vim/_editor.lua:0: E5560: nvim_exec2 must not be called in a lua loop callback 
local osc = require'osc'.new{
  transport = 'udp',
  recvAddr = '127.0.0.1',
  recvPort  = 9000,
}

osc:add_handler('/bar', function(data)
  print(vim.inspect(data))
end)
osc:add_handler("/foo", function(data)
  vim.cmd('%s/$/hello')
end)

osc:open()

Instead of

The answer is schedule_wrap:

osc:add_handler("/bobbins", vim.schedule_wrap(function(data)
    vim.cmd('%s/$/hello')
  end)
)