How can one create a directory dynamically in PL/pgSQL?
It looks good.  There might be two issues when using COPY {FROM | TO } PROGRAM though:


missing permissions on the directory you want to create the new one in.  With your present code this is unlikely, as your dir will be created in the Postgres data directory.  The directory would be created as owned by the OS user/group postgres, permissions set to 700.
you are trying this as a non-superuser.  That won't work - and also produces a different error:


ERROR:  must be superuser to COPY to or from an external program
HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.


Based on the above, your problem is the first case.  Check if the user has write permission on the target directory.