@mcp.tool()
def list_tables(schema: Optional[str] = None) -> Dict[str, Any]:
    """List user tables (exclude system schemas)."""
    try:
        with get_db_connection() as conn:
            with conn.cursor() as cur:
                if schema:
                    sql = """
                        SELECT table_name 
                        FROM information_schema.tables 
                        WHERE table_schema = %s 
                        AND table_type = 'BASE TABLE'
                        ORDER BY table_name
                    """
                    cur.execute(sql, (schema,))
                else:
                    sql = """
                        SELECT table_name 
                        FROM information_schema.tables 
                        WHERE table_schema NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                        AND table_type = 'BASE TABLE'
                        ORDER BY table_schema, table_name
                    """
                    cur.execute(sql)
                
                tables = [row['table_name'] for row in cur.fetchall()]
                return {"tables": tables}
    except Exception as e:
        logger.error(f"Error listing tables: {e}")
        return {"error": str(e), "tables": []}
