So as per my earlier comment, Emacs doesn't really support what you're asking for.
I would strongly recommend that you simply define a global command in the normal way, and make it behave appropriately based on the presence or not of a local variable (which could be directory-local). It can still be called from anywhere, but you would ensure that it never did something 'bad'.
Or come up with a key binding for your command -- it's easy [1] [2] to have key bindings which are only available in certain buffers.
If you're really dead-set on the command not being available via M-x
then the following is the cleanest and most robust approach I can think of (but it's still an ugly hack).
(defun my--real-command ()
"The real command; we'll leave this permanently defined."
(interactive)
(message "Hello, world."))
(defun my-pre-command-hook ()
"Define or undefine `my-command' based on `my-dir-local-flag'."
(when (eq this-command 'execute-extended-command)
(if (bound-and-true-p my-dir-local-flag)
(defalias 'my-command 'my--real-command)
(fmakunbound 'my-command))))
(add-hook 'pre-command-hook 'my-pre-command-hook)