I'd recommend against direct access to metadata.db. Its structure is not stable and generally speaking you dont want to have concurrent access to the db.
server.py already contains code to search and sort by various fields (it used for the HTMl content server), so you can just leverage that existing code if you modify server.py (have a look at the function library which generates the XML catalog of books for the content server to see sort and search in action). You'd have to modify the function stanza to handle multiple catalogs.
If you want to develop in perl, I'd suggest parsing the XML output of calibredb. It's very simple, so it shouldn't be a problem.